我正在使用 requests post 来发送一些数据,现在我已经将 requests.post 的超时值设置为 60 之类的值。其他与特定应用程序相关的类似问题,所以我想将其作为通用 python 错误提出。
这是我得到的错误:
failed to connect ('Connection aborted.', timeout('The write operation timed out'))
我假设这是因为出于某种原因我的线程无法及时发送所有数据,但我不确定所以只是想检查一下。所以:
这个错误是不是因为线程不能在超时时间内发送完所有的数据?
如果是这样,我是否可以将超时设置为仅在我发送完所有数据后才开始?我不想永远等待服务器响应,但显然我希望计时器在我发送所有数据时启动,而不是在函数调用开始时启动。 (我发送的数据大小不一)
最佳答案
如果您使用的是 python-request library ,您可以将“超时”参数指定为元组。第一个元素是“连接超时”,第二个是“读取超时”。
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。 Per the urllib3 docs ,将读取超时设置为 None 将永远等待服务器响应。但是,我同意永远等待是个坏主意。
您在请求中发送了多少数据?我通读了一些 python 请求代码,但找不到一种简单的方法来检测请求何时发送完毕。
作为概念证明,我写了 this code基于 urequests (micro requests)
它允许您将回调函数传递给 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)
关于请求后 : 'Connection aborted, timeout(' The write operation timed out') 的 Python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63992667/