-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession.py
More file actions
54 lines (42 loc) · 1.16 KB
/
session.py
File metadata and controls
54 lines (42 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import pickle
from Cookie import SimpleCookie
import sha,base64,os
sessiondir='sessions'
class sessionerror(Exception):
def __init__(self,msg):
self.msg=msg
def __str__(self):
return self.msg
def gensid():
return str(sha.new(base64.b64encode(os.urandom(16))).hexdigest())
def startsession(sessiondata={}):
sid=gensid()
sessiondata['sid']=sid
if(not os.path.exists(sessiondir)):
os.mkdir(sessiondir)
fileobj=open(os.path.join(sessiondir,sid),'w+')
pickle.dump(sessiondata,fileobj)
fileobj.close()
return sid
def set(key,val,request):
try:
c=SimpleCookie(request.environ['HTTP_COOKIE'])
fileobj=open(os.path.join('sessions',c['sid'].value),'r+')
dataobj=pickle.load(fileobj)
dataobj[key]=val
fileobj.seek(0,0)
pickle.dump(dataobj,fileobj)
fileobj.close()
except KeyError:
raise sessionerror('wrong cookies')
def get(key,request):
try:
c=SimpleCookie(request.environ['HTTP_COOKIE'])
fileobj=open(os.path.join('sessions',c['sid'].value),'r+')
dataobj=pickle.load(fileobj)
fileobj.close()
return dataobj.get(key,'')
except KeyError:
raise sessionerror('wrong cookies')
except IOError:
raise sessionerror('session not found')