Abe Miessler
Abe Miessler

Reputation: 85056

Best way to authenticate all requests?

I have a number of functions that are making calls to an api using requests. So a number of calls similar the one below (simplified for this example):

requests.get(url, data=data, auth=('user','password'))

All of the requests are going to be authenticated and I would like to find a cleaner way to authenticate all request rather than just including the auth=('user','password') portion in every call.

My first thought was to create a sub class that inherits from the requests class and then override the get function. Something like below:

class authRequests(requests):
  def get(url, data):
    return requests.get(url, data=data, auth=('user', 'password'))

and then use authRequests.get instead of requests.get. I don't have a ton python experience so this might not be a working example, but i'm wondering if this would be the right approach, or if I should be using a different method to do this?

Upvotes: 2

Views: 132

Answers (1)

alecxe
alecxe

Reputation: 473893

You should use the requests.Session() to persist things across different requests:

Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object

with requests.Session() as session:
    session.auth = ('user', 'password')

    session.get(url, data=data1)
    response = session.post(another_url, data=data2)

Upvotes: 2

Related Questions