python3.x - python连oanda的模拟交易api时现HTTP Error 401: UNAUTHORIZED?
漂亮男人
漂亮男人 2017-05-18 10:56:04
[Python讨论组]

用python3连oanda的模拟交易api时现HTTP Error 401: UNAUTHORIZED,新手求教:
import urllib.parse
import urllib.request

url = 'https://api-fxpractice.oanda....'
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
account_id = 'cawa11'
values = {'accountId':account_id}
headers = {'Authorization':'Bearer'+access_token}

data = urllib.parse.urlencode(values).encode("utf-8")

req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()

报错:
Traceback (most recent call last):
File "C:UserslenovoDesktopbb.py", line 36, in <module>

response = urllib.request.urlopen(req)

File "C:Python34liburllibrequest.py", line 161, in urlopen

return opener.open(url, data, timeout)

File "C:Python34liburllibrequest.py", line 469, in open

response = meth(req, response)

File "C:Python34liburllibrequest.py", line 579, in http_response

'http', request, response, code, msg, hdrs)

File "C:Python34liburllibrequest.py", line 507, in error

return self._call_chain(*args)

File "C:Python34liburllibrequest.py", line 441, in _call_chain

result = func(*args)

File "C:Python34liburllibrequest.py", line 587, in http_error_default

raise HTTPError(req.full_url, code, msg, hdrs, fp)

urllib.error.HTTPError: HTTP Error 401: UNAUTHORIZED

漂亮男人
漂亮男人

全部回复(2)
某草草
#Bearer后面少了一个空格
headers = {'Authorization':'Bearer '+access_token}
PHP中文网

问题已解决,谢谢各位关注:
import requests
import json
instruments = 'EUR_USD'
account_id = 'cawa11'
access_token = 'a554db3a48ac8180a6996a5547ba1663-ac5947e64456cc5842a34f4ce05e4380'
params = {'instruments':instruments,'accountId':account_id}
headers = {'Authorization':'Bearer '+access_token}
r = requests.get("https://api-fxpractice.oanda.com/v1/prices",headers = headers, params=params)
price = r.json()
print(price'prices'['instrument'].replace('_','/'),':',round((price'prices'['ask']+price'prices'['bid'])/2,4))
输出:EUR/USD : 1.0905

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号