csc309 webserver & javascript cookies
Here is the pickling and cookie webserver example using webpy that I presented in tutorial:
#!/usr/bin/env python
import os
import web
from pickle import load, dump
urls = (
'/', 'Index'
)
app = web.application(urls, globals())
# global session store & session id
SESSION_COUNT = 0
SESSIONS = {}
# methods to save & load data to files to persist
# session changes across restarts & crashes
data_fn = 'data.pkl'
def save_data():
fp = open(data_fn, 'w')
dump( (SESSIONS, SESSION_COUNT) , fp)
fp.close()
def load_data():
if not os.path.isfile(data_fn): return
global SESSIONS, SESSION_COUNT
fp = open(data_fn, 'r')
SESSIONS, SESSION_COUNT = load(fp)
fp.close()
# restore our session data
load_data()
def parse_cookies():
cookies_str = web.ctx.env['HTTP_COOKIE']
return dict([ c.strip().split('=')
for c in cookies_str.split(';')])
class Index(object):
def GET(self):
web.header('Content-Type','text/html')
session = {}
# see if the user has our cookie already
if 'HTTP_COOKIE' in web.ctx.env:
cookies = parse_cookies()
for name, val in cookies.items():
web.debug('got cookie: %s = %s' % (name, val))
# grab the session based on the user's cookie
if 'session_id' in cookies:
web.debug('got session id')
session = SESSIONS[cookies['session_id']]
# check if we got a session, if not create a new one
if not session:
web.debug('missing session, creating new session')
global SESSION_COUNT
expires_date = 'Fri, 11-Dec-2010 11:59:59 GMT'
web.header('Set-Cookie', 'session_id=%s;'
' expires=%s;'
% (expires_date, SESSION_COUNT))
SESSIONS[str(SESSION_COUNT)] = session
SESSION_COUNT += 1
# update the session
session['visits'] = session.setdefault('visits', 0)+1
save_data()
return (str(web.ctx.env) +
" You've visited %s times!"
% session['visits'])
def POST(self):
self.GET()
if __name__ == "__main__":
# run the webserver
app.run()
And here is the example of using cookies in Javascript:
// Cookies in Javascript // The manual (tedious) way to set a cookie document.cookie = ‘ppkcookie1=testcookie;' +
' expires=Thu, 2 Aug 2010 20:47:11 UTC; path=/’; // The easy way // from http://www.quirksmode.org/js/cookies.html // if days == 0, the cookie expires when
// the user closes their browser function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = “; expires=”+date.toGMTString(); } else var expires = “”; document.cookie = name+”=”+value+expires+”; path=/”; } function readCookie(name) { var nameEQ = name + “=”; var ca = document.cookie.split(‘;’); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==’ ‘) c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length); }
} return null; } function eraseCookie(name) { createCookie(name,”“,-1); }