2016-06-15 67 views
2

我試圖通過使用Fitbit API來下載我的數據。我已經想出瞭如何獲得某一天的數據,這很好。這裏是curl命令我使用:如何將此curl命令轉換爲執行相同操作的Python代碼?

curl -i -H "Authorization: Bearer (here goes a very long token)" https://api.fitbit.com/1/user/-/activities/heart/date/2016-6-14/1d/1sec/time/00:00/23:59.json >> heart_rate_20160614.json 

不過,我想收集數百天的數據,我不想這樣做手工。所以我想我可以使用Python循環。我閱讀了其他一些主題,如this onethis one,但仍不知道如何使用urllib2將這些curl命令「翻譯」爲python語言。

我已經試過這樣:

import urllib2 
url = 'https://api.fitbit.com/1/user/-/activities/heart/date/today/1d/1sec/time/00:00/00:01.json' 
data = '{Authorization: Bearer (here goes a very long token)}' 
req = urllib2.Request(url,data) 
f = urllib2.urlopen(req) 

但得到一個錯誤說「HTTP錯誤404:未找到」

那麼什麼是「翻譯」這個curl命令到Python語言的正確方法?謝謝!

回答

3

問題來自Request對象的構造:默認情況下,第二個參數是您想要與請求一起傳遞的數據。相反,你必須指定你想傳遞標題。這是做到這一點的正確方法:

import urllib2 
url = 'https://api.fitbit.com/1/user/-/activities/heart/date/2016-6-14/1d/1sec/time/00:00/23:59.json' 
hdr = {'Authorization': 'Bearer (token)'} 
req = urllib2.Request(url,headers=hdr) 
f = urllib2.urlopen(req) 

這使用了401在我身邊,但應該與您的令牌一起工作。

你可以有更多的urllib2信息(和Request類)here

不過,我建議你看一看Requests,這在我看來,更易於使用,並非常有據可查。

希望它會有所幫助。

1

在我看來,您可以使用出色的lib requests,它比urllib更容易使用。

首先,pip install requests,然後在你的解釋:

import requests 
response = requests.get(url='https://api.fitbit.com/1/user/-/activities/heart/date/2016-6-14/1d/1sec/time/00:00/23:59.json', headers={'Authorization':'Bearer <TOKEN>'}) 
if response.ok: 
    print response.content 
else: 
    print "error", response.content 

從這裏你可以很容易地通過response.contentresponse.json()得到的迴應內容,如果它是一個JSON,並將其寫入文件。

相關問題