您可以改为侵入requests
hooks 系统,然后使用它来跟踪响应及其请求:
from requests import hooks
_orig_default_hooks = hooks.default_hooks
def my_default_hooks():
hooks = _orig_default_hooks()
hooks['response'].append(response_hook)
return hooks
hooks.default_hooks = my_default_hooks
# requests.models is imported by the requests package, so we need to ensure it's reference
# to default_hooks is updated too.
import requests.models
requests.models.default_hooks = my_default_hooks
def response_hook(r, **kw):
req = r.request
print req.headers
reqeuests.hooks.default_hooks()
每个创建的请求都会调用该函数,通过注入您自己的response
事件挂钩,您可以看到收到的每个响应。响应有一个.request
属性,它是一个PreparedRequest
实例,您可以在其上找到.headers
和.body
属性以供检查。