Skip to content Skip to sidebar Skip to footer

Python Authentication Cookies And Django Sessions

I am trying to create an external python client to access a django app. The client should authenticate a user, generate cookies and be able to access the pages just like any browse

Solution 1:

You need to post to the login page, save the cookie, then send the cookies along with other subsequent requests. Something like this:

importrequestscredentials= {'login': 'foo', 'password': 'secret'}
web = requests.post('http://localhost:8000/login',data=credentials)
secure_cookie = web.cookiesweb= requests.get('http://localhost:8000/secret_page',cookies=secure_cookie)
the_page = web.text

Solution 2:

Some possible issues in you code

  • no ending slash in "http://localhost:8000/login" for a POST which can not be redirected when APPEND_SLASH is enabled.
  • no csrf_token info in login_data_encoded. Does the login view has csrf_exempt decorated?
  • Is there any required field to pass?

You may also

  • check log of Django
  • check the content of cj
  • check the response of opener.open('http://localhost:8000/login', login_data_encoded), include code and current URL

Solution 3:

I was sending the POST request to the wrong url. It was meant to be sent to:

opener.open('http://localhost:8000/auth', login_data_encoded)

Sorry my mistake. I thought if I sent the request to the login page it would work but the login page was not going to the right view. After changing it to the url with the right view, its works.

Thank you for the answers they were really helpful.

Post a Comment for "Python Authentication Cookies And Django Sessions"