当使用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) 我有以下与会话相关的代码,必须连续运行。
import requests
http = requests.Session()
while True:
# if http is not good, then run http = requests.Session() again
response = http.get(....)
# process respons
# wait for 5 seconds
Run Code Online (Sandbox Code Playgroud)
注意:我将线路移出http = requests.Session()了循环。
如何检查会话是否正常工作?
不工作会话的一个示例可能是在 Web 服务器重新启动之后。或者负载均衡器重定向到不同的 Web 服务器。