Files
daily-schedule/message/request_message.py

49 lines
1.5 KiB
Python
Raw Permalink 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
from typing import Optional, Dict, Any, Union
def send_request(
url: str,
method: str,
params: Optional[Dict[str, Any]] = None,
data: Optional[Union[Dict[str, Any], str, bytes]] = None,
json: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
timeout: Union[int, tuple] = 10,
**kwargs
) -> requests.Response:
"""
发送 HTTP 请求的通用函数
Args:
url: 请求的 URL
method: HTTP 方法GET/POST/PUT/DELETE等
params: URL 查询参数(?key=value
data: 表单数据application/x-www-form-urlencoded
json: JSON 数据application/json
headers: 请求头
timeout: 超时时间默认10秒
**kwargs: 其他 requests 支持的参数(如 auth, cookies 等)
Returns:
requests.Response: 响应对象
Raises:
requests.exceptions.RequestException: 请求异常
"""
try:
response = requests.request(
method=method.upper(),
url=url,
params=params,
data=data,
json=json,
headers=headers,
timeout=timeout,
**kwargs
)
response.raise_for_status() # 自动检查HTTP状态码非2xx会抛异常
return response
except requests.exceptions.Timeout:
raise Exception(f"请求超时({timeout}秒未响应)")
except requests.exceptions.RequestException as e:
raise Exception(f"请求失败: {str(e)}")