请求后 : 'Connection aborted, timeout(' The write operation timed out') 的 Python 错误

标签 python python-3.x python-requests

我正在使用 requests post 来发送一些数据,现在我已经将 requests.post 的超时值设置为 60 之类的值。其他与特定应用程序相关的类似问题,所以我想将其作为通用 python 错误提出。

这是我得到的错误:

failed to connect  ('Connection aborted.', timeout('The write operation timed out'))

我假设这是因为出于某种原因我的线程无法及时发送所有数据,但我不确定所以只是想检查一下。所以:

  1. 这个错误是不是因为线程不能在超时时间内发送完所有的数据?

  2. 如果是这样,我是否可以将超时设置为仅在我发送完所有数据后才开始?我不想永远等待服务器响应,但显然我希望计时器在我发送所有数据时启动,而不是在函数调用开始时启动。 (我发送的数据大小不一)

最佳答案

如果您使用的是 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/

相关文章:

python - 如何添加一列 timedelta 并将其与另一列关联?

python - 在 tkinter 中获取子元素的宽度

python - 条件检查字符串没有给出我期望的行为

python - 使用 Python 测试 AWS lambda

用于多个条目的 Python Pivot

python - 如何提取 URL?

python - 使用Python中的请求迭代向API发送请求

python - 有没有办法全局覆盖请求的超时设置?

python - 如何在 Pandas 中获得连续滚动平均值?

python - Django如何自定义表名和外键字段