Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting HTTP User-Agent header with requests-oauthlib

I'm using the requests-oauthlib library to get a request token from an OAuth (v1) provider.

oauth = OAuth1Session(CONSUMER_KEY, client_secret=CONSUMER_SECRET,
                      signature_method=SIGNATURE_HMAC,
                      signature_type=SIGNATURE_TYPE_AUTH_HEADER)

resp = oauth.fetch_request_token(url=REQUEST_TOKEN_URL)

I'd like to send a custom User-Agent header with the request token fetch request and include some contact information in case there are ever any problems with my script. Can this be done?

like image 237
Adam Williams Avatar asked Jun 14 '26 09:06

Adam Williams


1 Answers

It's possible to pass in a client class to the OAuth1Session constructor. From the docblock in the relevant file:

"""
    :param client_class: A subclass of `oauthlib.oauth1.Client` to use with
                         `requests_oauthlib.OAuth1` instead of the default
"""

Within the oauthlib.oauth1.Client class, the _render(self, request, formencode=False, realm=None) method appears responsible for preparing the request. Since unrelated headers don't impact the base string that the request signature is created from, adding a new header/changing an existing User-Agent header shouldn't cause the signature to change in any way.

As such, we can create a custom client class, override the _render method and call the implementation in the parent class once we've added our header:

class CustomClient(Client):
    def _render(self, request, formencode=False, realm=None):
        request.headers['User-Agent'] = "FooClient/1.0"
        return super()._render(request, formencode, realm)

The code that instantiates OAuth1Session then simply needs to reference the above class:

oauth = OAuth1Session(CONSUMER_KEY, client_secret=CONSUMER_SECRET,
                          signature_method=SIGNATURE_HMAC,
                          signature_type=SIGNATURE_TYPE_AUTH_HEADER, client_class=CustomClient)
like image 164
Adam Williams Avatar answered Jun 16 '26 23:06

Adam Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!