自动向python请求添加头

2024-04-27 03:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个restapi客户机,用于与我们的某个服务对话。每一个请求都需要包含一个授权头,它受到Epoch时间、请求动词、数据、路径等的影响

我试图尽可能无缝地使用python请求模块,但不确定将头“注入”到每个请求中的最佳方式。在

在请求中似乎有一个“hook”的概念,但目前只有一个“response”钩子。在

我正在考虑扩展Session对象并重写“send”方法,添加头,然后将其传递给super(会话.发送)方法。在

我的Python在OOP和继承方面并不出色,但这正是我所尝试的

 class MySession(Session):
    def __init__(self, access_id=None, access_key=None):
        self.access_id = access_id
        self.access_key = access_key
        super(MySession, self).__init__()

    def send(self, request, **kwargs):
        method = request.method
        path = urlparse(request.url).path

        request.headers['Authorization'] = self.__create_security_header(method, path)
        request.headers['Content-Type'] = "application/json"

        return Session.send(self, request, **kwargs)

Tags: path方法keyselfnonesendidaccess
1条回答
网友
1楼 · 发布于 2024-04-27 03:45:05

我想您不需要重写send方法,因为您已经重写了__init__。在

class MySession(Session):

    def __init__(self, access_id=None, access_key=None):
        super(MySession, self).__init__()
        self.access_id, self.access_key = access_id, access_key

        # provided __create_security_header method is defined
        self.headers['Authorization'] = self.__create_security_header(method, path)
        self.headers['Content-Type'] = "application/json"

很可能就是这样。在

相关问题 更多 >