Files
SNAPI/CallServer.py
2025-09-15 11:26:56 +00:00

42 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests#导入必要的库
import json
from requests.exceptions import RequestException
from .. import PyWebPageAPI
UA = f"SolianForPythonApp/0.0.1(A) ({PyWebPageAPI.GetDeviceInfo()})"
def _make_request(method: str, url: str, headers: dict, params: dict = None, normal_codes: list = [200], request_body: dict = None) -> dict:
"""
params:
可选参数用于GET请求的查询参数
request_body:
可选参数用于POST和PATCH请求的请求体
normal_codes:
可选参数用于指定正常的HTTP状态码列表默认值为[200]
return:
字典类型,包含请求的响应数据或错误信息
内部辅助函数用于发送HTTP请求并处理响应
支持GET、POST、DELETE、PATCH请求
自动处理JSON格式的请求体和响应体
处理常见的HTTP错误码返回统一的错误信息格式"""
headers['User-Agent'] = UA#添加UA
try:
if method == 'GET':#请求类型选择
response = requests.get(url, headers=headers, params=params)
elif method == 'POST':
response = requests.post(url, headers=headers, data=json.dumps(request_body))
elif method == 'DELETE':
response = requests.delete(url, headers=headers, params=params)
elif method == 'PATCH':
response = requests.patch(url, headers=headers, data=json.dumps(request_body))
else:
return {"error": "Unsupported HTTP method"}
if response.status_code not in normal_codes:#不在计划内的错误码
return {"error": f"Unexpected status code: {response.status_code}"}
return response.json()
except json.JSONDecodeError:#json解析错误
return {"error": response.text}
except RequestException as e:
return {"error": str(e)}