Marek
Marek

Reputation: 1249

Persisten session based on cookies in Requests

Why my session still wants me to authenticate once I've done it?

def main(pswd):
    with session() as s:
        s.post('url',
               auth=('user', pswd),
              )

        response = s.get('url2', cookies=s.cookies)

        print(response.text)

Why is my session not persistent?

Console is printing after that:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title>
</head><body>
<h1>Authorization Required</h1>
<p>This server could not verify that you
are authorized to access the document
requested.  Either you supplied the wrong
credentials (e.g., bad password), or your
browser doesn't understand how to supply
the credentials required.</p>
</body></html>

Also I can do:

s.get('url', auth=('user', 'login')).text

and this will work, but for second s.get it will no work. I have to pass credentials one more time.

Upvotes: 0

Views: 65

Answers (1)

Alasdair
Alasdair

Reputation: 308829

When using a Session object with requests, you can set the authentication details as follows:

with session() as s:
    s.auth = ('user', 'pass')
    s.post(url)  # auth headers will be sent with this request
    s.post(url2)  auth headers will be sent with this request as well

Upvotes: 1

Related Questions