python3.x - The fifth question of getting json from python's simulated trading api with oanda
为情所困
为情所困 2017-05-24 11:35:19
0
2
1754

Sometimes it suddenly stops working after working normally for more than an hour without any error, or the error requests.packages.urllib3.exceptions.ProtocolError: ('Connection aborted.', BadStatusLine("''",)), etc. on the Internet Some places say that it is timed out, some say that the connection is https, and some say that it needs to be changed to python3.5 or above (I use python3.4)

The program is the original program in the previous questions plus a while True: loop, thank you

program:

import requests
import json

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后有空格

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'])

Error message:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connectionpool.py", line 554, in urlopen
    self._prepare_proxy(conn)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connectionpool.py", line 750, in _prepare_proxy
    conn.connect()
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connection.py", line 230, in connect
    self._tunnel()
  File "C:\Python34\lib\http\client.py", line 815, in _tunnel
    (version, code, message) = response._read_status()
  File "C:\Python34\lib\http\client.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:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\adapters.py", line 376, in send
    timeout=timeout
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connectionpool.py", line 609, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\util\retry.py", line 247, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\packages\six.py", line 309, in reraise
    raise value.with_traceback(tb)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connectionpool.py", line 554, in urlopen
    self._prepare_proxy(conn)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connectionpool.py", line 750, in _prepare_proxy
    conn.connect()
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\packages\urllib3\connection.py", line 230, in connect
    self._tunnel()
  File "C:\Python34\lib\http\client.py", line 815, in _tunnel
    (version, code, message) = response._read_status()
  File "C:\Python34\lib\http\client.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:\Users\lenovo\Desktop\hh.py", line 27, in <module>
    r = requests.get(url,headers = headers, params=params)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\api.py", line 67, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\api.py", line 53, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
  File "C:\Python34\lib\site-packages\requests-2.9.1-py3.4.egg\requests\adapters.py", line 426, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",))

The new error message that appears after making the modification as @prolifes said:
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] The connection attempt failed because the connecting party did not reply properly after a period of time or the connected host was unresponsive.

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, 'The connection attempt failed because the connecting party did not reply properly after a period of time or the connected host did not respond.', 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, 'The connection attempt failed because the connecting party did not reply properly after a period of time or the connected host did not respond.', 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

为情所困
为情所困

reply all(2)
滿天的星座

Encapsulate key codes into functions and add error handling to ensure that while true is not interrupted, and at the same time print information for troubleshooting

# coding: utf-8

import requests
import json
import 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) 
        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()
淡淡烟草味

The problem has been solved with the help of @prolifes, the procedure is as follows:

coding: utf-8

import requests
import json
import 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()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template