Struggle to fetch csrf token from cookiejar

I am using the below code based on this answer to store the authentication cookies in a file. This allows me to avoid having to log in every time I start the program.

Now fetching csrftoken from regular session cookies works well, but when I try to retrieve it from cookiejar using csrf = s.cookies['csrftoken']

I get

AttributeError: LWPCookieJar instance has no attribute '__getitem__'`

      

I understand this is because I am treating s.cookies as a list, even though it is now an LWPCookieJar object. I guess this leaves me with two options:

Or:

  • Extract the list from the object LWPCookieJar

    and then get the csrf token.
  • or, find the appropriate syntax to get the csrf token directly from LWPCookieJar

    .

How can i do this?


import os
import requests
from cookielib import LWPCookieJar

s = requests.Session()
s.cookies = LWPCookieJar('cookiejar')
if os.path.exists('cookiejar'):
    # Load saved cookies from the file and use them in a request
    print('loading saved cookies')
    s.cookies.load()        
else:
    # Create a new cookies file and set our Session cookies
    print('saving cookies')
    s.cookies.save()
r = s.get('http://httpbin.org/cookies')
print(r.text)
# Save the session cookies back to the file
s.cookies.save()

      

+3


source to share


1 answer


I finally figured it out. Not sure if it can be simplified.



import os, requests
from cookielib import LWPCookieJar

def login():
    global s
    s = requests.Session()
    if os.path.exists('cookiejar'):
        print('Cookies exist! Fast login.\r'),
        global csrf
        with open('cookiejar') as f:
            s.cookies = requests.utils.cookiejar_from_dict(pickle.load(f))
        csrf = s.cookies['csrftoken']
        print('csrf: {0}').format(csrf) # Debug information
    else:
        print('Cookies do not exist. Slow login.\r'),
        s.get('http://www.example.com/') # to get csrf
        csrf = s.cookies['csrftoken']
        data= dict(csrftoken=csrf, username="user", password="pass")
        s.post('https://www.example.com/login/', data=data, headers=headers)
        with open('cookiejar', 'w') as f:
            pickle.dump(requests.utils.dict_from_cookiejar(s.cookies), f)

      

0


source







All Articles