【问题标题】:python requests module doesnt work when curl works. What am I doing wrong?当 curl 工作时,python 请求模块不起作用。我究竟做错了什么?
【发布时间】:2016-02-01 08:00:54
【问题描述】:

我有一个 curl 请求和一个使用 python 请求模块到本地 Web 服务的类似请求。虽然 curl 请求正常工作,但通过 python 发出的请求并没有按预期工作,即不返回 json 响应。

关于为什么会发生这种情况的任何想法?使用 python 我仍然得到 200 响应,但是得到 HTML 响应文本而不是 curl 中的 json,并且响应是关于无效会话等的。

这是 curl 请求

root@weve1:~$ curl -k --GET --data "ajax=getPermissions&project=test&session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c" http://localhost:12320/manager
{
  "permissions" : [ {
    "permission" : [ "ADMIN" ],
    "username" : "azkaban"
  } ],
  "project" : "test",
  "projectId" : 92
}

这与python中的请求相同

root@weve1:~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> s=requests.get('http://localhost:12320/manager',data={'ajax':'getPermissions','project':'test','session.id':'5604d7ce-f3dd-4349-8957-563c2675ae5c'})
>>> s.json()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 741, in json
    return json.loads(self.text, **kwargs)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
>>> 

【问题讨论】:

  • 在尝试从 JSON 转换之前,也许先看看文本响应?
  • 我查看了 response.text,它是 html blob 而不是 json。我猜当发送给它的数据格式不正确时,该服务返回 html 而不是 json。我只是想知道可能出了什么问题
  • @poke .. 不,这不是 POST。当我执行 curl -x -POST 时,它不会返回任何数据

标签: python curl python-requests


【解决方案1】:

来自 curl 手册页:

-G/--get

使用此选项时,将使用 -d/--data 或 --data-binary 指定的所有数据在 HTTP GET 请求中使用,而不是在其他情况下使用的 POST 请求。数据将附加到带有“?”的 URL分隔符。

所以 curl 实际上是将参数作为查询字符串传递,即http://localhost:12320/manager?ajax=getPermissions&amp;project=test&amp;session.id=5604d7ce-f3dd-4349-8957-563c2675ae5c。

为了通过请求传递URL中的数据,您需要传递数据in the params argument:

data = { 'ajax': 'getPermissions', 'project': 'test', 'session.id': '5604d7ce-f3dd-4349-8957-563c2675ae5c' }
s = requests.get('http://localhost:12320/manager', params=data)

data 参数仅指实际的请求正文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2016-05-27
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多