[英]Python - Requests module - Receving streaming updates - Connection reset by peer
我已经在一个外汇提供商(OANDA)的实践帐户中构建了自己的python(3.2.1版)交易应用程序,但是在使用基于Linux debian的OS接收流价格时遇到了一些问题。
特别是,我遵循了他们的“ Python流传输率”指南,可在这里找到: http : //developer.oanda.com/rest-live/sample-code/ 。
我有一个线程调用函数“ connect_to_stream”,该函数打印出从服务器接收到的所有滴答声:
streaming_thread = threading.Thread(target=streaming.connect_to_stream, args=[])
streaming_thread.start()
stream.connect_to_stream函数的定义如下:
def connect_to_stream():
[..]#provider-related info are passed here
try:
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization' : 'Bearer ' + access_token,
'Connection' : 'keep-alive'
}
params = {'instruments' : instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers = headers, params = params)
pre = req.prepare()
resp = s.send(pre, stream = True, verify = False)
return resp
except Exception as e:
s.close()
print ("Caught exception when connecting to stream\n%s" % str(e))
if response.status_code != 200:
print (response.text)
return
for line in response.iter_lines(1):
if line:
try:
msg = json.loads(line)
print(msg)
except Exception as e:
print ("Caught exception when connecting to stream\n%s" % str(e))
return
msg变量包含为流式传输收到的滴答声。
问题是,我平均会收到三个小时的滴答声,然后断开连接,脚本会挂起而没有收到任何滴答声,或者抛出异常,原因是“对等连接重置”。
您能否对我在这里出什么问题分享任何想法? 它与请求库(可能是iter_lines)有关吗?
除非引发键盘异常,否则我希望无限期收到报价。
谢谢
对于我来说,服务关闭关闭超过3小时的连接似乎并不奇怪。
确保从幽灵客户端释放服务器套接字对他们而言可能是安全的。
因此,您可能应该在断开连接时重新连接。
try:
s = requests.Session()
url = "https://" + domain + "/v1/prices"
headers = {'Authorization' : 'Bearer ' + access_token,
'Connection' : 'keep-alive'
}
params = {'instruments' : instruments, 'accountId' : account_id}
req = requests.Request('GET', url, headers = headers, params = params)
pre = req.prepare()
resp = s.send(pre, stream = True, verify = False)
return resp
except SocketError as e:
if e.errno == errno.ECONNRESET:
pass # connection has been reset, reconnect.
except Exception as e:
pass # other exceptions but you'll probably need to reconnect too.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.