0

I have a django webapp and authentificate via the requests module

import requests

payload = {
    'action': 'login',
    'username': "username",
    'password': "password"
}


r = requests.post('https://example.org/auth', data=payload)
print r.headers
print r.text
print r.cookies

That works fine. But how can I make the session persistent in the browser, i.e. I want to open another tab of example.org and be already signed in?

Edit: I know about You can easily create a persistent session using:

 s = requests.session()

The question is rather about how to make the session persistent between several requests or browser tabs, i.e. how to store the cookie jar in the browser.

Martin Kapfhammer
  • 260
  • 1
  • 4
  • 18
  • possible duplicate of [Python Requests and persistent sessions](http://stackoverflow.com/questions/12737740/python-requests-and-persistent-sessions) – fredtantini Dec 31 '14 at 11:01
  • I want to call example.org/otherPage.html in another http request or even in another browser tab. Therefore the question is how to set the cookies so that the browser adds them in future requests. – Martin Kapfhammer Dec 31 '14 at 11:05

1 Answers1

0

Use session():

Session Objects

The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance.

So you can do:

from requests import session
with session() as s:
    #connexion
    req = s.post('https://example.org/auth', data=payload)
    #get another page
    req = s.get('https://example.org/otherPage.html')

You can also get cookies from one request:

>>> r = requests.get(url)    
>>> r.cookies['example_cookie_name']
'example_cookie_value'
>>> req1Cookies = r.cookies

and send the cookies you want with another request:

To send your own cookies to the server, you can use the cookies parameter:

>>> cookies = dict(cookies_are='working') 
>>> r = requests.get(url, cookies=cookies)

or

>>> r = requests.get(url, cookies=req1Cookies)
fredtantini
  • 15,966
  • 8
  • 49
  • 55