Skip to content

Commit 5fe4ff5

Browse files
committed
fix request timeout
1 parent 8f5831d commit 5fe4ff5

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

v2/functions.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,28 @@
55
import os
66
import base64
77
import urllib
8+
import time
89
from PIL import Image
910

11+
def request_with_retry(target_url, headers, payload, timeout=10, max_retries=3, retry_interval=5):
12+
"""
13+
发送带有超时和重试的 HTTP 请求
14+
:param target_url: 请求的 URL
15+
:param headers: 请求头
16+
:param payload: 请求体
17+
:param timeout: 超时时间,单位为秒
18+
:param max_retries: 最大重试次数
19+
:param retry_interval: 重试间隔时间,单位为秒
20+
:return: HTTP 响应
21+
"""
22+
for i in range(max_retries):
23+
try:
24+
response = requests.request("GET", target_url, headers=headers, data=payload, timeout=timeout)
25+
return response
26+
except requests.exceptions.Timeout:
27+
print(f"请求超时,正在进行第 {i+1} 次重试...")
28+
time.sleep(retry_interval)
29+
raise requests.exceptions.Timeout(f"请求超时,已重试 {max_retries} 次")
1030

1131
def send_msg_q_wechat(hook_url, content):
1232
try:
@@ -137,7 +157,8 @@ def download_sunset_image(rise=True, save_dir="temp"):
137157
"Accept-Language": "zh-CN,zh;q=0.9",
138158
}
139159

140-
response = requests.request("GET", target_url, headers=headers, data=payload)
160+
# response = requests.request("GET", target_url, headers=headers, data=payload)
161+
response = request_with_retry(target_url, headers, payload, timeout=10, max_retries=3, retry_interval=5)
141162

142163
# 保存为图片
143164
if not os.path.exists(save_dir):

0 commit comments

Comments
 (0)