python3.x - python連oanda的模擬交易api獲取json問(wèn)題第五問(wèn)
問(wèn)題描述
在正常工作1個(gè)多小時(shí)后有時(shí)突然停止工作沒(méi)有任何報(bào)錯(cuò),或者報(bào)錯(cuò)requests.packages.urllib3.exceptions.ProtocolError: (’Connection aborted.’, BadStatusLine('’’',)),網(wǎng)上其他地方有的說(shuō)是超時(shí)、有的說(shuō)是說(shuō)連的是https、有的說(shuō)要換成python3.5或以上(我用的是python3.4)
程序就是原來(lái)上幾問(wèn)中的程序再加個(gè)while True :的循環(huán),謝謝
程序:
import requestsimport jsonurl = 'https://api-fxpractice.oanda.com/v1/prices'instruments = ’EUR_USD,USD_CAD’account_id = ’cawa11’params = {’instruments’:instruments,’accountId’:account_id}access_token = ’a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380’ headers = {’Connection’: ’Keep-Alive’, ’Accept-Encoding’: ’gzip,deflate’, ’Authorization’:’Bearer ’+access_token} #Bearer后有空格while True : r = requests.get(url,headers = headers, params=params) price = r.json() print(r.json()) print(price[’prices’][0][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][0][’ask’]+price[’prices’][0][’bid’])/2,4),’ ’,price[’prices’][0][’time’]) print(price[’prices’][1][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][1][’ask’]+price[’prices’][1][’bid’])/2,4),’ ’,price[’prices’][1][’time’])
報(bào)錯(cuò)信息:
Traceback (most recent call last): File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 554, in urlopen self._prepare_proxy(conn) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 750, in _prepare_proxy conn.connect() File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py', line 230, in connect self._tunnel() File 'C:Python34libhttpclient.py', line 815, in _tunnel (version, code, message) = response._read_status() File 'C:Python34libhttpclient.py', line 321, in _read_status raise BadStatusLine(line)http.client.BadStatusLine: ’’During handling of the above exception, another exception occurred:Traceback (most recent call last): File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py', line 376, in send timeout=timeout File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 609, in urlopen _stacktrace=sys.exc_info()[2]) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilretry.py', line 247, in increment raise six.reraise(type(error), error, _stacktrace) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3packagessix.py', line 309, in reraise raise value.with_traceback(tb) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 554, in urlopen self._prepare_proxy(conn) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 750, in _prepare_proxy conn.connect() File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py', line 230, in connect self._tunnel() File 'C:Python34libhttpclient.py', line 815, in _tunnel (version, code, message) = response._read_status() File 'C:Python34libhttpclient.py', line 321, in _read_status raise BadStatusLine(line)requests.packages.urllib3.exceptions.ProtocolError: (’Connection aborted.’, BadStatusLine('’’',))During handling of the above exception, another exception occurred:Traceback (most recent call last): File 'C:UserslenovoDesktophh.py', line 27, in <module> r = requests.get(url,headers = headers, params=params) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py', line 67, in get return request(’get’, url, params=params, **kwargs) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py', line 53, in request return session.request(method=method, url=url, **kwargs) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py', line 468, in request resp = self.send(prep, **send_kwargs) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py', line 576, in send r = adapter.send(request, **kwargs) File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py', line 426, in send raise ConnectionError(err, request=request)requests.exceptions.ConnectionError: (’Connection aborted.’, BadStatusLine('’’',))
按@prolifes說(shuō)的進(jìn)行修改后出現(xiàn)的新的報(bào)錯(cuò)信息:Traceback (most recent call last): File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 559, in urlopen
body=body, headers=headers)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 345, in _make_request
self._validate_conn(conn)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 784, in _validate_conn
conn.connect()
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py', line 252, in connect
ssl_version=resolved_ssl_version)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilssl_.py', line 305, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File 'C:Python34libssl.py', line 365, in wrap_socket
_context=self)
File 'C:Python34libssl.py', line 583, in init
self.do_handshake()
File 'C:Python34libssl.py', line 810, in do_handshake
self._sslobj.do_handshake()
TimeoutError: [WinError 10060] 由于連接方在一段時(shí)間后沒(méi)有正確答復(fù)或連接的主機(jī)沒(méi)有反應(yīng),連接嘗試失敗。
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py', line 376, in send
timeout=timeout
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 609, in urlopen
_stacktrace=sys.exc_info()[2])
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilretry.py', line 247, in increment
raise six.reraise(type(error), error, _stacktrace)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3packagessix.py', line 309, in reraise
raise value.with_traceback(tb)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 559, in urlopen
body=body, headers=headers)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 345, in _make_request
self._validate_conn(conn)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py', line 784, in _validate_conn
conn.connect()
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py', line 252, in connect
ssl_version=resolved_ssl_version)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilssl_.py', line 305, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File 'C:Python34libssl.py', line 365, in wrap_socket
_context=self)
File 'C:Python34libssl.py', line 583, in init
self.do_handshake()
File 'C:Python34libssl.py', line 810, in do_handshake
self._sslobj.do_handshake()
requests.packages.urllib3.exceptions.ProtocolError: (’Connection aborted.’, TimeoutError(10060, ’由于連接方在一段時(shí)間后沒(méi)有正確答復(fù)或連接的主機(jī)沒(méi)有反應(yīng),連接嘗試失敗。’, None, 10060, None))
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File 'C:UserslenovoDesktopii.py', line 30, in run
r = requests.get(url,headers = headers, params=params)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py', line 67, in get
return request(’get’, url, params=params, **kwargs)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py', line 53, in request
return session.request(method=method, url=url, **kwargs)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py', line 468, in request
resp = self.send(prep, **send_kwargs)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py', line 576, in send
r = adapter.send(request, **kwargs)
File 'C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py', line 426, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: (’Connection aborted.’, TimeoutError(10060, ’由于連接方在一段時(shí)間后沒(méi)有正確答復(fù)或連接的主機(jī)沒(méi)有反應(yīng),連接嘗試失敗。’, None, 10060, None))
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File 'C:UserslenovoDesktopii.py', line 133, in <module>
run()
File 'C:UserslenovoDesktopii.py', line 128, in run
print(traceback.format_exc())
NameError: name ’traceback’ is not defined
問(wèn)題解答
回答1:把關(guān)鍵代碼封裝成函數(shù),并加上錯(cuò)誤處理,保證while true不中斷,同時(shí)打印信息去排查
# coding: utf-8import requestsimport jsonimport tracebackdef run(): try:url = 'https://api-fxpractice.oanda.com/v1/prices'instruments = ’EUR_USD,USD_CAD’account_id = ’cawa11’params = {’instruments’:instruments,’accountId’:account_id}access_token = ’a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380’ headers = {’Connection’: ’Keep-Alive’, ’Accept-Encoding’: ’gzip,deflate’, ’Authorization’:’Bearer ’+access_token} #Bearer后有空格 r = requests.get(url,headers = headers, params=params) price = r.json()print(r.json())print(price[’prices’][0][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][0][’ask’]+price[’prices’][0][’bid’])/2,4),’ ’,price[’prices’][0][’time’])print(price[’prices’][1][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][1][’ask’]+price[’prices’][1][’bid’])/2,4),’ ’,price[’prices’][1][’time’]) except:print traceback.format_exc()if __name__ == ’__main__’: while True:run()回答2:
在@prolifes的幫助下問(wèn)題已解決,程序如下:
coding: utf-8import requestsimport jsonimport traceback
def run():
try: url = 'https://api-fxpractice.oanda.com/v1/prices' instruments = ’EUR_USD,USD_CAD’ account_id = ’cawa11’ params = {’instruments’:instruments,’accountId’:account_id}access_token = ’a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380’ headers = {’Connection’: ’Keep-Alive’, ’Accept-Encoding’: ’gzip,deflate’, ’Authorization’:’Bearer ’+access_token} #Bearer后有空格 r = requests.get(url,headers = headers, params=params,timeout=5) price = r.json() print(r.json()) print(price[’prices’][0][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][0][’ask’]+price[’prices’][0][’bid’])/2,4),’ ’,price[’prices’][0][’time’]) print(price[’prices’][1][’instrument’].replace(’_’,’/’),’:’,round((price[’prices’][1][’ask’]+price[’prices’][1][’bid’])/2,4),’ ’,price[’prices’][1][’time’])except: #print traceback.format_exc() pass
if name == ’__main__’:
while True: run()
相關(guān)文章:
1. java - 自己制作一個(gè)視頻播放器,遇到問(wèn)題,用的是內(nèi)置surfaceview類(lèi),具體看代碼!2. javascript - vue 移動(dòng)端的input 數(shù)字輸入優(yōu)化3. 服務(wù)器端 - 采用nginx做web服務(wù)器,C++開(kāi)發(fā)應(yīng)用程序 出現(xiàn)拒絕連接請(qǐng)求?4. javascript - 有什么兼容性比較好的辦法來(lái)判斷瀏覽器窗口的類(lèi)型?5. 關(guān)于docker下的nginx壓力測(cè)試6. python - pandas按照列A和列B分組,將列C求平均數(shù),怎樣才能生成一個(gè)列A,B,C的dataframe7. 為什么我ping不通我的docker容器呢???8. javascript - nidejs環(huán)境設(shè)置操作一直出現(xiàn)這種問(wèn)題怎么解決?9. javascript - npm start 運(yùn)行’webpack-dev-server’報(bào)錯(cuò) Cannot find module ’webpack’10. java 隨機(jī)延遲執(zhí)行
