【发布时间】:2016-10-28 18:45:38
【问题描述】:
我正在尝试重构一些代码,其中许多 HTTP 请求是使用 requests 模块发出的。其中许多请求(部分)具有相同的标头,因此我想使用 Session objects 来“预填充”这些标头。
但是,在这种情况下,我很难让多重继承工作。这是我尝试过的:
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 标头。如何结合 AuthorizedSession 和 JSONSession 类来查看两者?
【问题讨论】:
标签: python session python-requests multiple-inheritance