I am trying to stay logged in to a website while I run a program continuously. The session eventually times out though.
Here is my test program:
import urllib
import urllib2
import cookielib
import re
url = 'https://www.locationary.com/'
data = urllib.urlencode({"inUserName":"EMAIL", "inUserPass":"PASSWORD"})
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1'))
opener.addheaders.append(('Referer', 'http://www.locationary.com/'))
opener.addheaders.append(('Cookie','site_version=REGULAR; JSESSIONID=781FD0C497FB596954BB78B1323215F6'))
request = urllib2.Request("https://www.locationary.com/index.jsp?ACTION_TOKEN=tile_loginBar_jsp$JspView$LoginAction", data)
response = opener.open(request)
page = opener.open(url).read()
print re.findall(r'<title>(.*)</title>', page)
h = response.info().headers
print h
The output is:
['Home Page']
['Server: nginx/1.0.8\r\n', 'Date: Fri, 10 Aug 2012 17:07:47 GMT\r\n', 'Content-Type: text/html;charset=UTF-8\r\n', 'Transfer-Encoding: chunked\r\n', 'Connection: close\r\n', 'Set-Cookie: PSESSIONID=533e2fb9fda008d5d16bfbdc9b9a6afed0e5ac54; Path=/\r\n', 'P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"\r\n', 'Set-Cookie: PSESSIONID=533e2fb9fda008d5d16bfbdc9b9a6afed0e5ac54; Path=/\r\n']
I experimented…and if I took out the JSESSIONID part of the cookie, my output would be for the home page of the website as if I WASN’T logged in..so it would say “Locationary.com” instead of “Home Page.” When I DO put the JSESSIONID in, everything works, but the server also sets a cookie called PSESSIONID…what does all this mean…and how can I make it so my session doesn’t time out? Do I have to find another JSESSIONID every, say, half an hour?
Cookies is a mechanism used in order to create the illusion of sessions over a session-less protocol (e.g. http). You can read all about it, just google it (there are many good explanations around).
If you simply want it to work properly, whenever you get a
set-cookieheader, keep that value (replacing any old value by the same name), and send it with every request you send. I’d suggest using a dictionary, for robustness.Regarding timing out – let the website deal with that, you just follow his orders (i.e. set the cookies 🙂 .