session auth in python

Viewed 25300

Using session from requests module in python, it seems that the session sends authorization only with first request, I can't understand why this happened.

import requests
session = requests.Session()
session.auth = (u'user', 'test')
session.verify = False
response = session.get(url='https://my_url/rest/api/1.0/users')

If I look for this response request headers I see:

{'Authorization': 'Basic auth_data', 'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.12.3'}

but if I send next request using the same or not url:

response = session.get(url='https://my_url/rest/api/1.0/users')

I can see that there is no auth header in request anymore:

print response.request.headers
{'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.12.3'}

And I'm getting 401 response because of it.

Why is it so? Shouldn't session send auth with every request made using it? How can I send auth data with every request using session?

2 Answers

I didn't find any reliable answer on how to pass, auth info while making request's session in python. So below is my finding:

with requests.sessions.Session() as session:
    session.auth = ("username", "password")
    
    # Make any requests here without provide auth info again
    session.get("http://www.example.com/users")
Related