【问题标题】:Pre-filling request headers using classes derived from requests.Session in Python使用派生自 Python 中的 requests.Session 的类预填充请求标头
【发布时间】: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 标头。如何结合 AuthorizedSessionJSONSession 类来查看两者?

【问题讨论】:

    标签: python session python-requests multiple-inheritance


    【解决方案1】:

    我发现如果我更简单地定义AuthorizedJSONSession 如下:

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

    生成的请求现在更新了 AuthorizationContent-Type 标头:

    我了解到,当一个类从多个类继承,而这些类又从同一个基类继承时,Python 就“足够聪明”,只需使用super 进行初始化。

    【讨论】:

    • 我已经切换到 Python 3,其中super 可以以零参数形式调用:super().__init__(auth_token=auth_token)
    猜你喜欢
    • 1970-01-01
    • 2022-01-09
    • 2021-01-16
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多