2014-01-29 75 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