From 857dd9bd1da8e74095754e293417bd69e4e6ce56 Mon Sep 17 00:00:00 2001 From: Cxx0822 <1556464090@qq.com> Date: Tue, 28 Oct 2025 09:25:27 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E9=87=8D=E6=9E=84request=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 6 ++--- message/request_message.py | 49 ++++++++++++++++++++++++++++++++++++++ message/wechat_message.py | 19 +++++++++------ work/daily_stock.py | 7 +++--- work/daily_weather.py | 13 ++++++---- 5 files changed, 76 insertions(+), 18 deletions(-) create mode 100644 message/request_message.py diff --git a/main.py b/main.py index 320bf5d..b1df2fa 100644 --- a/main.py +++ b/main.py @@ -68,9 +68,9 @@ def run_schedule(): def main(): logger.info("程序启动,开始设置定时任务...") - # daily_weather_task() - # daily_stock_task() - # daily_order_supper_task() + daily_weather_task() + daily_stock_task() + daily_order_supper_task() setup_schedule() try: diff --git a/message/request_message.py b/message/request_message.py new file mode 100644 index 0000000..c4a996e --- /dev/null +++ b/message/request_message.py @@ -0,0 +1,49 @@ +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)}") \ No newline at end of file diff --git a/message/wechat_message.py b/message/wechat_message.py index 02dd898..b7f89bd 100644 --- a/message/wechat_message.py +++ b/message/wechat_message.py @@ -1,8 +1,9 @@ from enum import Enum -import requests import json +from message.request_message import send_request + webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send' webhook_key_estun = 'f09eb098-f709-4fc6-83b5-4a08a8431b8f' webhook_key_sweet_hut = '5ccae111-43a1-4672-a94f-0d34713259c0' @@ -24,17 +25,21 @@ def send_wechat_message(message_type: MessageEnum, message: str, has_sweet_hut=F case MessageEnum.MARKDOWN2: wechat_message = {"msgtype": "markdown_v2", "markdown_v2": {"content": message}} - requests.post( - webhook_url, + send_request( + url=webhook_url, + method="POST", headers={"Content-Type": "application/json"}, params={'key': webhook_key_estun}, - data=json.dumps(wechat_message, ensure_ascii=False).encode('utf-8') + data=json.dumps(wechat_message, ensure_ascii=False).encode('utf-8'), + timeout=5 ) if has_sweet_hut: - requests.post( - webhook_url, + send_request( + url=webhook_url, + method="POST", headers={"Content-Type": "application/json"}, params={'key': webhook_key_sweet_hut}, - data=json.dumps(wechat_message, ensure_ascii=False).encode('utf-8') + data=json.dumps(wechat_message, ensure_ascii=False).encode('utf-8'), + timeout=5 ) diff --git a/work/daily_stock.py b/work/daily_stock.py index 723d65e..42ed628 100644 --- a/work/daily_stock.py +++ b/work/daily_stock.py @@ -1,12 +1,13 @@ -import requests +from message.request_message import send_request stock_url = 'http://push2.eastmoney.com/api/qt/stock/get' estun_id = '0.002747' def get_today_stock(company_id=estun_id): - response = requests.get( - stock_url, + response = send_request( + url=stock_url, + method='GET', params={'secid': company_id} ) diff --git a/work/daily_weather.py b/work/daily_weather.py index 2b4be48..7881b53 100644 --- a/work/daily_weather.py +++ b/work/daily_weather.py @@ -1,6 +1,7 @@ -import requests from datetime import datetime +from message.request_message import send_request + weather_url = 'https://p478kygkjw.re.qweatherapi.com' weather_api_key = '4aa47f183c694aaa812ff018be8270e4' nanjing_location = '101190101' @@ -8,19 +9,21 @@ nanjing_location = '101190101' def get_today_weather(city_location=nanjing_location): url = f'{weather_url}/v7/weather/3d' - response = requests.get( + + response = send_request( url=url, + method="GET", headers={'X-QW-Api-Key': f'{weather_api_key}'}, - params={'location': city_location} - ) + params={'location': city_location}) return response.json() def get_today_indices(city_location=nanjing_location): url = f'{weather_url}/v7/indices/1d' - response = requests.get( + response = send_request( url=url, + method="GET", headers={'X-QW-Api-Key': f'{weather_api_key}'}, params={'location': city_location, 'type': '0'} )