【问题标题】:Curl works but python requests doesn'tCurl 有效,但 python 请求无效
【发布时间】:2018-03-08 03:26:53
【问题描述】:

当我卷曲时,我得到一个响应:

root@3d7044bac92f:/home/app/tmp# curl -H "Content-type: application/json" -X GET https://github.com/timeline.json -k 

{"message":"Hello there, wayfaring stranger. If you\u2019re reading this then you probably didn\u2019t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}

但是,当我向同一个 URL 发出 python 请求时,我得到一个状态 410。

import requests

headers = {
    'Content-type': 'application/json',
}

r = requests.get('https://github.com/timeline.json')
print r.json

root@3d7044bac92f:/home/app/tmp# python rest.py 
<bound method Response.json of <Response [410]>>

什么给了?

主机是一个标准的 Ubuntu docker 镜像,只安装了 Curl 和一些 python 模块。 Python -V 是 2.7

注意:我查看了这个问题,但我无法远程登录到上面的服务器,因此该解决方案不适用于我: Curl works but not Python requests

【问题讨论】:

  • 你可以print r.text 代替吗?
  • curl 也会收到 410 响应。 curl -icurl -v 将显示响应标头。

标签: python python-2.7 http docker curl


【解决方案1】:

您在程序中至少犯了两个错误。

1) 您没有为requests.get() 调用指定data=headers 参数。试试这个:

 r = requests.get('https://github.com/timeline.json', data=data, headers=headers)

2) .json 是一个方法,而不是响应对象的数据属性。作为一种方法,必须调用它才能有效。试试这个:

print r.json()

【讨论】:

  • json() 就是它。谢谢!
猜你喜欢
  • 2014-09-18
  • 2023-03-19
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
  • 2018-10-22
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多