2014-01-29 76 views
2

编辑 - 因为我无法Strava这个标签这里是文档,如果你有兴趣 - http://strava.github.io/api/Get请求活动strava V3 API的Python

我通过认证得很好,并获得的access_token(和我运动员信息)在一个response.read。

我在下一步遇到问题: 我想返回有关特定活动的信息。

import urllib2 
    import urllib 

    access_token = str(tp[3]) #this comes from the response not shown 
    print access_token 

    ath_url = 'https://www.strava.com/api/v3/activities/108838256' 

    ath_val = values={'access_token':access_token} 

    ath_data = urllib.urlencode (ath_val) 

    ath_req = urllib2.Request(ath_url, ath_data) 

    ath_response = urllib2.urlopen(ath_req) 

    the_page = ath_response.read() 

    print the_page 

误差

Traceback (most recent call last): 
     File "C:\Users\JordanR\Python2.6\documents\strava\auth.py", line 30, in <module> 
     ath_response = urllib2.urlopen(ath_req) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 124, in urlopen 
     return _opener.open(url, data, timeout) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 389, in open 
     response = meth(req, response) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 502, in http_response 
     'http', request, response, code, msg, hdrs) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 427, in error 
     return self._call_chain(*args) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 361, in _call_chain 
     result = func(*args) 
     File "C:\Users\JordanR\Python2.6\lib\urllib2.py", line 510, in http_error_default 
     raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
    HTTPError: HTTP Error 404: Not Found 

404是一个谜,因为我知道这个活动的存在呢?

'access_token'是否正确的标题信息? 该文档(http://strava.github.io/api/v3/activities/#get-details)使用授权:承载?我不确定liburl如何编码信息的承载部分?

对不起,如果我的一些术语有点偏离,我是新手。

回答了这个坏男孩。

import requests as r 
access_token = tp[3] 

ath_url = 'https://www.strava.com/api/v3/activities/108838256' 
header = {'Authorization': 'Bearer 4b1d12006c51b685fd1a260490_example_jklfds'} 

data = r.get(ath_url, headers=header).json() 

它需要在“词典”中添加“承载”部分。

感谢您的帮助idClark

+0

我也无法理解承载参数。你有没有尝试从命令行击中端点?如果我做'curl -XGET https://www.strava.com/api/v3/activities/111008284 -H“授权:持证人my_access_token_goes_here”| jq'。''我可以找回JSON就好了。稍后我会尝试使用Python。 – idclark

回答

6

我更喜欢使用第三方Requests模块。您的确需要遵循文档并使用the API

中记录的授权:标头。然后,我们可以创建一个字典,其中的关键是Authorization它的值是一个字符串Bearer access_token

#install requests from pip if you want 
import requests as r 
url = 'https://www.strava.com/api/v3/activities/108838256' 
header = {'Authorization': 'Bearer access_token'} 
r.get(url, headers=header).json() 

如果你真的想使用的urllib2

#using urllib2 
import urllib2 
req = urllib.Request(url) 
req.add_header('Authorization', 'Bearer access_token') 
resp = urllib2.urlopen(req) 
content = resp.read() 

只记得access_token需求是字符串值,例如acc09cds09c097d9c097v9

+0

谢谢@idclark看这个。我有一个请求并失败了,我确实得到了一个JSON响应,所以取得了一些成功,尽管它告诉我授权失败了。这是一个愚蠢的问题,在标题行应该“承载access_token”是我的文字字符串值?在问题中修改了 – user1633891

+0

。 – user1633891