如何调试请求库?

Ram*_*amy 5 python curl python-requests

我正在尝试将我的 python 脚本从发出 curl 命令转换os.system()为使用请求。我以为我会使用 pycurl,但这个问题让我信服。问题是我从服务器返回了一个错误,我在使用 r.text 时可以看到这个错误(来自这个答案),但我需要更多信息。有没有更好的方法来调试正在发生的事情?

我认为这个问题与将我的 --data 标志从 curl/pycurl 转换为请求有关。我已经创建了一个我之前传递给 --data 的参数的字典。我的猜测是其中之一无效,但我如何才能获得更多信息才能确定?

例子:

headers2 = {"Accept":"*/*", \
"Content-Type":"application/x-www-form-urlencoded", \
"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36", \
"Origin":"https://somedomain.com", \
"X-Requested-With":"XMLHttpRequest", \
"Connection":"keep-alive", \
"Accept-Language":"en-US,en;q=0.8", \
"Referer":"https://somedomain.com/release_cr_new.html?releaseid=%s&v=2&m=a&prev_release_id=%s" % (current_release_id, previous_release_id), \
"Host":"somedomain.com", \
"Accept-Encoding":"gzip,deflate,sdch", \
"Cookie":'cookie_val'}

for bug_id in ids:
  print bug_id
  data = {'dump_json':'1','releaseid':current_release_id, 'v':'2','m':'a','prev_release_id': previous_release_id,'bug_ids': bug_id, 'set_cols':'sqa_status&sqa_updates%5B0%5D%5Bbugid%5D=' + bug_id + '&sqa_updates%5B0%5D%5Bsqa_status%5D=6'}
  print 'current_release_id' , data['releaseid']
  print 'previous_release_id', data['prev_release_id']
  r = requests.post(post_url, data=json.dumps(data), headers=headers2)
  print r.text
Run Code Online (Sandbox Code Playgroud)

我得到的输出是一个非常通用的 html 消息,我以前在以错误的方式查询服务器时看到过。所以我知道我至少到达了正确的服务器。

我真的不期待任何输出。这应该只是发布到服务器并更新数据库中的字段。

Jon*_*han 5

http 响应剖析

示例(加载此页面)

HTTP/1.1 200 OK
Cache-Control: public, max-age=60
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Expires: Fri, 27 Sep 2013 19:22:41 GMT
Last-Modified: Fri, 27 Sep 2013 19:21:41 GMT
Vary: *
X-Frame-Options: SAMEORIGIN
Date: Fri, 27 Sep 2013 19:21:41 GMT
Content-Length: 12706

<!DOCTYPE html>
<html>
... truncated rest of body ...
Run Code Online (Sandbox Code Playgroud)
  1. 第一行是状态行,由状态代码状态文本组成
  2. 标头是键/值对。标题以一个空的新行结束。空行表示没有更多的标头,有效载荷/正文的开头如下。
  3. body消耗消息的其余部分。

下面解释如何提取3个部分:

状态行

使用以下命令获取服务器发回的状态行

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404

>>> bad_r.raise_for_status()
Traceback (most recent call last):
  File "requests/models.py", line 832, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error
Run Code Online (Sandbox Code Playgroud)

(来源)

标题:

r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
# response headers: 
r.headers
# request headers:
r.request.headers
Run Code Online (Sandbox Code Playgroud)

身体

使用r.text.

请求后编码

您在请求中发送到服务器的“内容类型”应该与您实际发送的内容类型相匹配。在您的情况下,您正在发送 json 但告诉服务器您正在发送表单数据(如果您未指定,这是默认设置)。

从上面显示的标题中:

"Content-Type":"application/x-www-form-urlencoded",

但是您的 request.post 调用集data=json.dumps(data)是 JSON。标题应该说:

"Content-type": "application/json",