Pre-filling 使用 Python 中的 requests.Session 派生的 类 请求 headers

Pre-filling request headers using classes derived from requests.Session in Python

我正在尝试重构一些使用 requests module. Many of these requests have (partially) the same headers, so I would like to 'pre-fill' these using Session objects.

发出许多 HTTP 请求的代码

但是,在这种情况下,我很难使多重继承发挥作用。这是我尝试过的:

import requests, time

requestbin_URL = 'http://requestb.in/1nsaz9y1'      # For testing only; remains usable for 48 hours
auth_token = 'asdlfjkwoieur182932385'               # Fake authorization token

class AuthorizedSession(requests.Session):
    def __init__(self, auth_token):
        super(AuthorizedSession, self).__init__()
        self.auth_token = auth_token
        self.headers.update({'Authorization': 'token=' + self.auth_token})

class JSONSession(requests.Session):
    def __init__(self):
        super(JSONSession, self).__init__()
        self.headers.update({'content-type': 'application/json'})

class AuthorizedJSONSession(AuthorizedSession, JSONSession):
    def __init__(self, auth_token):
        AuthorizedSession.__init__(self, auth_token=auth_token)
        JSONSession.__init__(self)

""" These two commented-out requests work as expected """
# with JSONSession() as s:
#     response = s.post(requestbin_URL, data={"ts" : time.time()})

# with AuthorizedSession(auth_token=auth_token) as s:
#     response = s.post(requestbin_URL, data={"key1" : "value1"})

""" This one doesn't """
with AuthorizedJSONSession(auth_token=auth_token) as s:
    response = s.post(requestbin_URL, data={"tag" : "some_tag_name"})

如果我在 http://requestb.in/1nsaz9y1?inspect 检查最后一个请求的结果,我会看到以下内容:

似乎 Content-Type 字段已正确设置为 application/json;但是,我没有看到带有假身份验证令牌的 Authorization header。我怎样才能将 AuthorizedSessionJSONSession 类 结合起来才能看到两者?

我发现如果我按如下更简单地定义 AuthorizedJSONSession,请求就可以工作:

class AuthorizedJSONSession(AuthorizedSession, JSONSession):
    def __init__(self, auth_token):
        super(AuthorizedJSONSession, self).__init__(auth_token=auth_token)

生成的请求现在已经更新了 AuthorizationContent-Type headers:

我了解到,当 class 继承自多个 class,而这些 class 又继承自相同的基础 class,那么 Python 是 'smart enough' 简单地使用 super 来初始化。