Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log out of Requests Session in Python

I have successfully logged in to a site using python and sending a POST request with username and password as payload.

When I then go to the same site in a browser, the website informs me that someone is currently logged in to my account (guess who).

My question is this: how do I log out of the request session?

So far I have tried clearing cookies using c.cookies.clear() after finding this question on stackoverflow: Clear cookies from Requests Python

I have verified that cookies are created and then are cleared, but I still run in to the same login duplication when using a browser subsequently.

I have checked the Requests documentation and a number of previous questions, but I can't find an answer.

For you reference, I have pasted a general version of the code below.

Also for you information, when I logout of the browser a GET request is sent. Is this something I need to simluate? I have already tried sending it along with the cookies, but the same result. This seems like something that should be simple. At the moment I can work with it by logging out via browser, but long term it will be pain.

Your assistance is appreciated. Cheers, smaug.

import requests

payload = {'userid': 'my username value', 
           'passwd': 'my password value'
}

with requests.Session() a c:
    c.post('http://www.examplewebsite.com/login.html', data = payload)
    print 'cookies', requests.utils.dict_from_cookiejar(c.cookies)
    c.cookies.clear()
    print 'cookies', requests.utils.dict_from_cookiejar(c.cookies)
like image 246
smaug Avatar asked Oct 28 '25 09:10

smaug


1 Answers

If the website has an API that requires you to logout, requests can't possibly know that. You have to explicitly make the logout API request.

While requests has something called a Session, and many web service frameworks do too, a session isn't actually a persistent connection between two computers like a TCP socket.

  • A web service framework session is essentially just a way to pass an ID back and forth to the client in cookies and map it to some database record or equivalent. It still only sees one request at a time, and the only way it knows you're done, unless you tell it, is by not seeing your session ID for a while.
  • A requests session is essentially just a place to store cookies across multiple requests the way a browser would, so web service frameworks' sessions will work the same way they would in a browser.

So, clearing the cookies doesn't do anything that's visible to the server. The server can't see anything you do, except for the requests that you send.

like image 144
abarnert Avatar answered Oct 29 '25 23:10

abarnert