cari

Rumah  >  Soal Jawab  >  teks badan

python3.x - Python menyambung api dagangan simulasi oanda untuk mendapatkan soalan json soalan ke-5

Kadangkala ia tiba-tiba berhenti berfungsi selepas bekerja seperti biasa selama lebih daripada sejam tanpa sebarang ralat, atau ralat requests.packages.urllib3.exceptions.ProtocolError: ('Sambungan dibatalkan.', BadStatusLine("''",)) dilaporkan di tempat lain di Internet ada yang mengatakan ia telah tamat masa, ada yang mengatakan ia disambungkan ke https, ada yang mengatakan ia perlu ditukar kepada python3.5 ke atas (saya menggunakan python3.4)

Program ini ialah atur cara asal dalam soalan sebelumnya ditambah gelung sementara Benar:, terima kasih

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

Mesej ralat:

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("''",))

Mesej ralat baharu selepas membuat pengubahsuaian seperti yang dikatakan @prolifes:
Traceback (panggilan terbaharu terakhir):
Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 559, dalam urlopen

body=body, headers=headers)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 345, dalam _make_request

self._validate_conn(conn)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 784, dalam _validate_conn

conn.connect()

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py", baris 252, dalam sambungan

ssl_version=resolved_ssl_version)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilssl_.py", baris 305, dalam ssl_wrap_socket

return context.wrap_socket(sock, server_hostname=server_hostname)

Fail "C:Python34libssl.py", baris 365, dalam wrap_socket

_context=self)

Fail "C:Python34libssl.py", baris 583, dalam

init

self.do_handshake()

Fail "C:Python34libssl.py", baris 810, dalam do_handshake

self._sslobj.do_handshake()

TimeoutError: [WinError 10060] Percubaan sambungan gagal kerana pihak penyambung tidak membalas dengan betul selepas tempoh masa atau hos yang disambungkan tidak bertindak balas.

Semasa pengendalian pengecualian di atas, pengecualian lain berlaku:

Traceback (panggilan terakhir terakhir):

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py", baris 376, dalam hantar

timeout=timeout

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 609, dalam urlopen

_stacktrace=sys.exc_info()[2])

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilretry.py", baris 247, dalam kenaikan

raise six.reraise(type(error), error, _stacktrace)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3packagessix.py", baris 309, dalam reraise

raise value.with_traceback(tb)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 559, dalam urlopen

body=body, headers=headers)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 345, dalam _make_request

self._validate_conn(conn)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connectionpool.py", baris 784, dalam _validate_conn

conn.connect()

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3connection.py", baris 252, dalam sambungan

ssl_version=resolved_ssl_version)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestspackagesurllib3utilssl_.py", baris 305, dalam ssl_wrap_socket

return context.wrap_socket(sock, server_hostname=server_hostname)

Fail "C:Python34libssl.py", baris 365, dalam wrap_socket

_context=self)

Fail "C:Python34libssl.py", baris 583, dalam init

self.do_handshake()

Fail "C:Python34libssl.py", baris 810, dalam do_handshake

self._sslobj.do_handshake()

requests.packages.urllib3.exceptions.ProtocolError: ('Sambungan dibatalkan.', TimeoutError(10060, 'Percubaan sambungan gagal kerana pihak penyambung tidak membalas dengan betul selepas tempoh masa atau hos yang disambungkan tidak bertindak balas.', Tiada, 10060, Tiada))

Semasa pengendalian pengecualian di atas, pengecualian lain berlaku:

Traceback (panggilan terakhir terakhir):
Fail "C:UserslenovoDesktopii.py", baris 30, sedang dijalankan

r = requests.get(url,headers = headers, params=params)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py", baris 67, dalam get

return request('get', url, params=params, **kwargs)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsapi.py", baris 53, dalam permintaan

return session.request(method=method, url=url, **kwargs)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py", baris 468, dalam permintaan

resp = self.send(prep, **send_kwargs)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestssessions.py", baris 576, dalam hantar

r = adapter.send(request, **kwargs)

Fail "C:Python34libsite-packagesrequests-2.9.1-py3.4.eggrequestsadapters.py", baris 426, dalam hantar

raise ConnectionError(err, request=request)

requests.exceptions.ConnectionError: ('Sambungan dihentikan.', TimeoutError(10060, 'Percubaan sambungan gagal kerana pihak penyambung tidak membalas dengan betul selepas tempoh masa atau hos yang disambungkan tidak bertindak balas.', Tiada, 10060, Tiada))

Semasa pengendalian pengecualian di atas, pengecualian lain berlaku:

Traceback (panggilan terbaharu terakhir):
Fail "C:UserslenovoDesktopii.py", baris 133, dalam <modul>

run()

Fail "C:UserslenovoDesktopii.py", baris 128, sedang dijalankan

print(traceback.format_exc())

NameError: nama 'traceback' tidak ditakrifkan

为情所困为情所困2750 hari yang lalu1763

membalas semua(2)saya akan balas

  • 滿天的星座

    滿天的星座2017-05-24 11:37:19

    Ingkapsulkan kod kunci ke dalam fungsi dan tambah pengendalian ralat untuk memastikan bahawa walaupun benar tidak terganggu, dan pada masa yang sama mencetak maklumat untuk penyelesaian masalah

    # 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()

    balas
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-24 11:37:19

    Masalah telah diselesaikan dengan bantuan @prolifes, prosedurnya adalah seperti berikut:

    pengekodan: utf-8

    permintaan import
    import json
    import jejak balik

    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
    

    jika nama == '__utama__':

    while True:
        run()

    balas
    0
  • Batalbalas