我试图重构一些使用requests模块生成许多HTTP请求的代码。其中许多请求都有(部分)相同的标题,因此我希望预先填写'这些使用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
类来查看两者?
答案 0 :(得分:0)
如果我更简单地定义<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
<div id="container2"></div>
,我发现请求有效:
AuthorizedJSONSession
结果请求现已更新了class AuthorizedJSONSession(AuthorizedSession, JSONSession):
def __init__(self, auth_token):
super(AuthorizedJSONSession, self).__init__(auth_token=auth_token)
和Authorization
标题:
我已经明白,当一个类继承自多个类,而这些类继承自同一个基类时,Python就足够“聪明”,只需使用Content-Type
进行初始化。