上传文件至 /
This commit is contained in:
42
CallServer.py
Normal file
42
CallServer.py
Normal file
@@ -0,0 +1,42 @@
|
||||
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)}
|
Reference in New Issue
Block a user