简体   繁体   English

如何检测python请求中的断开连接保持活动连接?

[英]How to detect a disconnect in python-requests keep alive connection?

I am using python-requests to connect to a live feed. 我正在使用python-requests连接到实时源。 After I connect, I use iter_lines to go over the data as it arrives. 连接后,我使用iter_lines在数据到达时检查数据。 I am trying to detect a disconnect when it happens, currently without success. 当它发生时,我试图检测断开连接,目前没有成功。

The way I detect disconnects currently, is by waiting a maximum of 30 seconds for a new line to arrive, and if it doesn't, I restart the connection. 我当前检测到断开连接的方式是等待最多30秒才能到达新线路,如果没有,我重新启动连接。 The problem is that I miss the data that arrives within these 30 seconds. 问题是我错过了这30秒内到达的数据。

As a test, I tried turning off my wifi in the middle and seeing if anything (like Response.status_code) changes, but it does not. 作为测试,我尝试在中间关闭我的wifi,看看是否有任何变化(如Response.status_code),但事实并非如此。

Example code: 示例代码:

r = requests.get(url, stream=True)

while True:
     time.sleep(1)
     print(r.status_code)

I expected the print to show 200 when connected and SOME_SORT_OF_ERROR when I turn the wifi off, but I keep on seeing 200. 我希望打印在连接时显示200,在关闭wifi时显示SOME_SORT_OF_ERROR,但我一直看到200。

Does anyone know of a way to detect the disconnect? 有谁知道检测断开连接的方法?

As the python requests doc says, the keep alive is 100% automatic in a session. 正如python请求doc所说,keep alive在会话中是100%自动的。 You should read the lines this way: 你应该这样读取这些行:

r = requests.get(url, stream=True)

for line in r.iter_lines():
    if line:
        print json.loads(line)

You can read more about it here 你可以在这里阅读更多相关信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM