【问题标题】:how to convert this curl command to some Python codes that do the same thing?如何将此 curl 命令转换为一些执行相同操作的 Python 代码?
【发布时间】:2016-06-15 06:58:43
【问题描述】:

我正在尝试使用 Fitbit API 下载我的数据。我已经想出了如何获取某一天的数据,这很好。这是我使用的 curl 命令:

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 Error 404: Not Found”

那么将这个 curl 命令“翻译”成 python 语言的正确方法是什么?谢谢!

【问题讨论】:

    标签: python curl request urllib2


    【解决方案1】:

    问题来自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,我认为它更易于使用,并且有很好的文档记录。

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      在我看来,您可以使用优秀的库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)轻松获取响应内容,并将其写入文件。

      【讨论】:

        猜你喜欢
        • 2022-01-16
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 2013-05-23
        • 1970-01-01
        • 2014-08-28
        • 1970-01-01
        相关资源
        最近更新 更多