我正在使用请求库读取XML事件,如下所示的代码。一旦请求开始,我该如何引发连接丢失错误?服务器模拟HTTP推送/长轮询-> http://en.wikipedia.org/wiki/Push_technology#Long_polling,默认情况下不会结束。如果10分钟后没有新消息,则应退出while循环。
服务器推送可以通过命令行使用curl进行测试:
import requests
from time import time
if __name__ == '__main__':
#: Set a default content-length
content_length = 512
try:
requests_stream = requests.get('http://agent.mtconnect.org:80/sample?interval=0', stream=True, timeout=2)
while True:
start_time = time()
#: Read three lines to determine the content-length
for line in requests_stream.iter_lines(3, decode_unicode=None):
if line.startswith('Content-length'):
content_length = int(''.join(x for x in line if x.isdigit()))
#: pause the generator
break
#: Continue the generator and read the exact amount of the body.
for xml in requests_stream.iter_content(content_length):
print "Received XML document with content length of %s in %s seconds" % (len(xml), time() - start_time)
break
except requests.exceptions.RequestException as e:
print('error: ', e)
服务器推送可以通过命令行使用curl进行测试:
curl http://agent.mtconnect.org:80/sample\?interval\=0
requests
模块添加了这5秒钟的延迟。 - Sunny Nandarequests_stream.iter_lines
是一个阻塞调用(很可能是这样),那么没有其他方法可以做到,因为在等待数据时,循环中的超时函数不会被调用。 - Sunny Nanda