0

I am trying to create a rest api client for talking to one of our services. Every request needs to include an authorisation header which is compromised of Epoch times, request verb, data, path etc.

I'm trying to use the python requests module as seamlessly as possible, but am unsure the best way to "inject" a header into every request.

There seems to be a concept of "hooks" in requests, but currently there is only a "response" hook.

I was considering extending the Session object and overriding the "send" method, adding the header and then passing it up to the super (Session.send) method.

My Python isn't fantastic when it comes to OOP and Inheritance, but this is what I have tried

 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)

1 Answer 1

1

I guess you don't need to override the send method, since you have already overriden the __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"

Most likely that should do.

Sign up to request clarification or add additional context in comments.

1 Comment

Will that create a new header for each request though? as the header is a hash of method, uri etc it needs to be generated just before the request is sent.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.