Python请求:指定参数时使用列表

时间:2015-07-02 20:15:35

标签: python python-requests

尝试从Oanda的API获取货币报价。这是我的代码:

s = requests.Session()
url = "https://stream-fxpractice.oanda.com/v1/prices"
headers = {'Authorization': 'Bearer ' + access_token}
params = {'instruments': pairs_oanda, 'accountId': account_id}
resp = s.get(url, headers=headers, params=params, stream=True)

access_token和account_id是API的身份验证。当我向pairs_oanda提供一个货币对(例如“EUR_USD”)时,它工作正常,产生以下网址:

https://streamfxpractice.oanda.com/v1/prices?instruments=GBP_USD&accountId=*******

但是,当我提供货币对列表时,例如

["EUR_USD", "GBP_USD"]

到pairs_oanda,我收到了这个网址:

https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD&instruments=GBP_USD&accountId=*******

但是,我需要的网址才能正确访问API:

https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD%2CGBP_USD&accountId=*******

无论如何都要让Requests以不同的方式解析列表吗?

1 个答案:

答案 0 :(得分:3)

API希望您使用逗号来分隔货币对。你必须自己这样做;在这里使用str.join()

pairs_oanda = ["EUR_USD", "GBP_USD"]
params = {'instruments': ','.join(pairs_oanda), 'accountId': account_id}

%2C字符序列是以{code}编码的,

>>> from urlparse import unquote
>>> unquote('%2C')
','

requests会为您提供引用,前提是您为其指定了不带引号的参数值:

>>> from requests import Request
>>> url = "https://stream-fxpractice.oanda.com/v1/prices"
>>> pairs_oanda = ["EUR_USD", "GBP_USD"]
>>> params = {'instruments': ','.join(pairs_oanda), 'accountId': 'foobarbaz'}
>>> r = Request('GET', url, params=params)
>>> r.prepare().url
'https://stream-fxpractice.oanda.com/v1/prices?instruments=EUR_USD%2CGBP_USD&accountId=foobarbaz'