繁体   English   中英

使用从request.Session派生的类预填充请求标头

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

我正在尝试重构一些使用请求模块发出许多HTTP请求的代码。 这些请求中有许多具有(部分)相同的标头,因此我想使用Session对象 “预填充”这些标头。

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

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标头。 如何合并AuthorizedSessionJSONSession类以查看两者?

我发现,如果我更简单地如下定义AuthorizedJSONSession ,则该请求有效:

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

现在,结果请求已更新了AuthorizationContent-Type标头:

在此处输入图片说明

我了解到,当一个类从多个类继承而又从同一个基类继承时,Python足够“聪明”,可以简单地使用super进行初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM