如果您正在使用python请求库 https://pypi.org/project/requests/,您可以将“timeout”参数指定为元组。第一个元素是“连接超时”,第二个元素是“读取超时”。
requests.get('http://google.com', timeout=(10,200) # give it 10 seconds to connect to the server, and timeout if server does not send any data back for 200+ seconds
requests 在底层使用 urrlib3.util.Timeout 。根据 urllib3 文档 https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html,将读取超时设置为 None 将永远等待服务器响应。但是,我同意永远等待是一个坏主意。
您在请求中发送了多少数据?我通读了一些 python 请求代码,但找不到一种简单的方法来检测请求何时完成发送。
作为概念证明我写了这段代码 https://github.com/GrantGMiller/request_with_event基于urequests(微请求) https://github.com/micropython/micropython-lib/blob/master/urequests/urequests.py
它允许您将回调函数传递给 requests.get()。该回调将在所有请求数据发送后、服务器接收到任何数据之前触发。
import time
def sent_callback():
print('The request has finished sending at', time.time())
resp = get('http://google.com', send_callback=sent_callback)
print('response received at', time.time())
print('resp.text=', resp.text)