当使用Python 2.7 urllib2从API检索数据时,我收到错误[Errno 104] Connection reset by peer.什么导致错误,以及如何处理错误,以便脚本不会崩溃?
ticker.py
def urlopen(url):
response = None
request = urllib2.Request(url=url)
try:
response = urllib2.urlopen(request).read()
except urllib2.HTTPError as err:
print "HTTPError: {} ({})".format(url, err.code)
except urllib2.URLError as err:
print "URLError: {} ({})".format(url, err.reason)
except httplib.BadStatusLine as err:
print "BadStatusLine: {}".format(url)
return response
def get_rate(from_currency="EUR", to_currency="USD"):
url = "https://finance.yahoo.com/d/quotes.csv?f=sl1&s=%s%s=X" % (
from_currency, to_currency)
data = urlopen(url)
if "%s%s" % (from_currency, to_currency) in data:
return float(data.strip().split(",")[1])
return None
counter = 0
while True: …Run Code Online (Sandbox Code Playgroud) 我在Python 3.4中使用Asyncio,我将尝试解释我在这一点上正在做的事情以及导致问题的原因。
一方面,我有一个带阻塞操作的UDP连接框架,我要从该流中获取数据并创建以SSE格式传递给客户端的json。这一切都很好。
我遇到的问题是,如果我什么也不做,则无法正确处理客户端断开连接,而客户端断开连接,我将开始遇到此错误:
WARNING [selector_events:613] socket.send() raised exception.
Run Code Online (Sandbox Code Playgroud)
由于循环仍在运行,因此我一直在研究彻底打破循环并触发.close()的方法,但是我遇到的示例问题令我无法解决,而且在线资源也不多。
似乎实际可行的一个示例是尝试从客户端读取一行,并且如果该字符串为空字符串,则表示客户端已断开连接。
while True:
data = (yield from client_reader.readline())
if not data: #client disconnected
break
Run Code Online (Sandbox Code Playgroud)
但是,在大约十条消息之后,所有发送给客户端的消息都停止了,我认为这是因为如果我关闭了客户端,则挂起后,它挂在了“数据=(来自client_reader.readline()的产量)”上,那么它确实关闭了,并且“结束连接”确实被调用。任何想法为什么它可能会挂起?我认为目前我对Asyncio有一个很好的处理,但是这个让我感到困惑。
注意:location()和status()是我从UDP套接字获取信息的两个调用-我已经使用相同的代码成功运行了多个小时而没有出现问题-减去了客户端断开连接线。
clients = {}
def accept_client(client_reader, client_writer):
task = asyncio.Task(handle_client(client_reader, client_writer))
clients[task] = (client_writer)
def client_done(task):
del clients[task]
client_writer.close()
log.info("End Connection")
log.info("New Connection")
task.add_done_callback(client_done)
@asyncio.coroutine
def handle_client(client_reader, client_writer):
data = {'result':{'status':'Connection Ready'}}
yield from postmessage(data,client_writer)
while True:
data = (yield from client_reader.readline())
if not data: #client disconnected
break
data = yield from asyncio.wait_for(location(),
timeout=1.0)
yield …Run Code Online (Sandbox Code Playgroud)