在我的情况下,我使用请求库调用贝宝的API通过HTTPS。不幸的是,我从贝宝得到一个错误,贝宝支持无法找出错误是什么或什么原因造成的。他们想让我“请提供整个请求,包括标题”。

我该怎么做呢?


当前回答

r = requests.get('https://api.github.com', auth=('user', 'pass'))

R是一个响应。它有一个request属性,其中包含您需要的信息。

r.request.allow_redirects  r.request.headers          r.request.register_hook
r.request.auth             r.request.hooks            r.request.response
r.request.cert             r.request.method           r.request.send
r.request.config           r.request.params           r.request.sent
r.request.cookies          r.request.path_url         r.request.session
r.request.data             r.request.prefetch         r.request.timeout
r.request.deregister_hook  r.request.proxies          r.request.url
r.request.files            r.request.redirect         r.request.verify

R.request.headers给出了头文件:

{'Accept': '*/*',
 'Accept-Encoding': 'identity, deflate, compress, gzip',
 'Authorization': u'Basic dXNlcjpwYXNz',
 'User-Agent': 'python-requests/0.12.1'}

然后r.request.data将主体作为映射。你可以用urllib转换它。Urlencode如果他们喜欢:

import urllib
b = r.request.data
encoded_body = urllib.urlencode(b)

根据响应的类型,.data-属性可能会丢失,取而代之的是.body-属性。

其他回答

详细配置选项可能允许您看到您想要的结果。文档中有一个例子。

注意:阅读下面的评论:详细配置选项似乎不再可用。

没有一个日志系统可以完全工作(至少在2.26请求中,非常旧的版本可能有另一种行为)

好的解决方案是使用“挂钩”,并在细节发生时打印出来。

这里有很好的解释:https://findwork.dev/blog/advanced-usage-python-requests-timeouts-retries-hooks/

在“打印一切”下,

但如果链接失效,这里是重要的部分

import requests
from requests_toolbelt.utils import dump

def logging_hook(response, *args, **kwargs):
    data = dump.dump_all(response)
    print(data.decode('utf-8'))

http = requests.Session()
http.hooks["response"] = [logging_hook]

http.get("https://api.openaq.org/v1/cities", params={"country": "BA"})

这次的结果将是发送查询和接收响应的完整跟踪。

我已经成功地尝试了POST和许多标题:它工作。 不要忘记pip install requests_toolbelt。

# Output
< GET /v1/cities?country=BA HTTP/1.1
< Host: api.openaq.org

> HTTP/1.1 200 OK
> Content-Type: application/json; charset=utf-8
> Transfer-Encoding: chunked
> Connection: keep-alive
>
{
   "meta":{
      "name":"openaq-api",
      "license":"CC BY 4.0",
      "website":"https://docs.openaq.org/",
      "page":1,
      "limit":100,
      "found":1
   },
   "results":[
      {
         "country":"BA",
         "name":"Goražde",
         "city":"Goražde",
         "count":70797,
         "locations":1
      }
   ]
}

如果你使用的是python2。X,尝试安装urllib2打开器。这应该打印出您的标题,尽管您可能必须将其与您正在使用的其他打开器结合起来以击中HTTPS。

import urllib2
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)))
urllib2.urlopen(url)

调试HTTP本地请求的一个更简单的方法是使用netcat。如果你跑了

nc -l 1234

您将开始在端口1234上监听HTTP连接。您可以通过http://localhost:1234/foo/foo/....访问它

在终端上,您将看到发送到端点的原始数据。例如:

POST /foo/foo HTTP/1.1
Accept: application/json
Connection: keep-alive
Host: example.com
Accept-Language: en-en
Authorization: Bearer ay...
Content-Length: 15
Content-Type: application/json

{"test": false}

一个简单的方法:在最近版本的请求中启用日志记录。X或更高。)

请求使用http。客户端和日志模块配置,以控制日志记录的详细程度,如下所述。

示范

摘自链接文档的代码:

import requests
import logging

# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
    import http.client as http_client
except ImportError:
    # Python 2
    import httplib as http_client
http_client.HTTPConnection.debuglevel = 1

# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

requests.get('https://httpbin.org/headers')

示例输出

$ python requests-logging.py 
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org
send: 'GET /headers HTTP/1.1\r\nHost: httpbin.org\r\nAccept-Encoding: gzip, deflate, compress\r\nAccept: */*\r\nUser-Agent: python-requests/1.2.0 CPython/2.7.3 Linux/3.2.0-48-generic\r\n\r\n'
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: application/json
header: Date: Sat, 29 Jun 2013 11:19:34 GMT
header: Server: gunicorn/0.17.4
header: Content-Length: 226
header: Connection: keep-alive
DEBUG:requests.packages.urllib3.connectionpool:"GET /headers HTTP/1.1" 200 226