2015-04-14 92 views
0

我試圖從API(oanda)獲取簡單的JSON貨幣匯率響應。
但接收各種錯誤代碼,如'無效語法'。python中curl請求的問題

這是我更新的代碼:

import requests 
import json 

from optparse import OptionParser 

def connect_to_stream(): 
    """ 
    Environment   <Domain> 
    fxTrade    stream-fxtrade.oanda.com 
    fxTrade Practice  stream-fxpractice.oanda.com 
    sandbox    stream-sandbox.oanda.com 
    """ 

    # Replace the following variables with your personal ones 
    domain = 'stream-fxpractice.oanda.com' 
    access_token = 'xxxxxxxxxxxxxxxx' 
    account_id = 'xxxxxxxxx' 
    instruments = "EUR_USD" 

    try: 
     s = requests.Session() 
     url = "https://" + domain + "/v1/prices" 
     headers = {'Authorization' : 'Bearer ' + access_token, 
        # 'X-Accept-Datetime-Format' : 'unix' 
        } 
     params = {'instruments' : instruments, 'accountId' : account_id} 
     req = requests.Request('GET', url, headers = headers, params = params) 
     pre = req.prepare() 
     resp = s.send(pre, stream = True, verify = False) 
     return resp 
    except Exception as e: 
     s.close() 
     print "Caught exception when connecting to stream\n" + str(e) 


response = urllib2.urlopen("https://api-fxpractice.oanda.com/v1/prices?instruments=EUR_USD") 
    data = json.load(response) 
    print data 

對不起,我編輯的代碼,並留出了錯誤信息。我是,然而,能夠通過這裏https://github.com/oanda/oandapy使用OANDA的Python包裝來解決這個問題。

+1

也許你也可以分享你得到的錯誤? – pagid

+0

不要嗚咽。避免不必要的背景。另外,您應該添加您收到的確切錯誤消息。 –

+0

@Nathaniel Ford感謝哥們指出我過度的wh,聲,沒有意識到我是如此煩人。我會嘗試發佈我以前的錯誤,以及.. – MacD

回答

1

該網址無效,我建議您檢查API是否最近發生了變化,因爲搜索結果顯示其他人過去曾嘗試過使用它。在嘗試訪問Chrome中的網址時,我收到以下信息:

由於DNS查找失敗,找不到api-practice.oanda.com上的服務器。 DNS是將網站名稱翻譯爲Internet地址的網絡服務 。此錯誤通常是由於沒有 連接到Internet或錯誤配置的網絡而造成的。它也可能是由於DNS服務器無響應或防火牆阻止Google Chrome訪問網絡造成的。

錯誤代碼:DNS_PROBE_FINISHED_NXDOMAIN

而且,我會堅持使用請求庫或urllib2的。你的問題底部的請求可以被改寫自:

response = urllib2.urlopen("https://api-fxpractice.oanda.com/v1/prices?instruments=EUR_USD") 
data = json.load(response) 
print data 

到:

r = requests.get("https://api-fxpractice.oanda.com/v1/prices?instruments=EUR_USD") 
data = r.json() 
print data 

編輯:網址更新爲匹配問題編輯。

https://api-practice.oanda.com/v1/prices?instruments=EUR_USD

https://api-fxpractice.oanda.com/v1/prices?instruments=EUR_USD

+0

對不起,該網址是api-fxpractice.oanda.com。我添加你的修訂版後,我得到這個錯誤 - 你這個請求需要授權,'u'code':3} - 任何想法?更新網址以及 – MacD

+0

你有一個oanda用戶訪問令牌嗎?你需要在請求中傳遞它。 –

+0

是的,我只是把它拿出來。如果有人需要它,我可以加回來嗎? – MacD

0

請做一個ipconfig /從服務器的命令提示符FLUSHDNS和你最有可能得到的結果。