forked from phith0n/Minos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesession.py
86 lines (74 loc) · 2.94 KB
/
filesession.py
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 Mitchell Chu
import os
from os.path import join, exists, isdir
import datetime
from driver import SessionDriver
from extends.torndsession.session import SessionConfigurationError
utcnow = datetime.datetime.utcnow
try:
import cPickle as pickle # py2
except:
import pickle # py3
class FileSession(SessionDriver):
"""
System File to save session object.
"""
DEFAULT_SESSION_POSITION = './#_sessions' # default host is '#_sessions' directory which is in current directory.
"""
Session file default save position.
In a recommendation, you need give the host option.when host is missed, system will use this value by default.
Additional @ Version: 1.1
"""
def __init__(self, **settings):
"""
Initialize File Session Driver.
settings section 'host' is recommended, the option 'prefix' is an optional.
if prefix is not given, 'default' is the default.
host: where to save session object file, this is a directory path.
prefix: session file name's prefix. session file like: prefix@session_id
"""
super(FileSession, self).__init__(**settings)
self.host = settings.get("host", self.DEFAULT_SESSION_POSITION)
self._prefix = settings.get("prefix", 'default')
if not exists(self.host):
os.makedirs(self.host, 0700) # only owner can visit this session directory.
if not isdir(self.host):
raise SessionConfigurationError('session host not found')
def get(self, session_id):
session_file = join(self.host, self._prefix + session_id)
if not exists(session_file): return {}
rf = file(session_file, 'rb')
session = pickle.load(rf)
rf.close()
now = utcnow()
expires = session.get('__expires__', now)
if expires >= now:
return session
return {}
def save(self, session_id, session_data, expires=None):
session_file = join(self.host, self._prefix + session_id)
session_data = session_data if session_data else {}
if not expires:
session_data.update("__expires__", expires)
wf = file(session_file, 'wb')
pickle.dump(session_data, wf)
wf.close()
def clear(self, session_id):
session_file = join(self.host, self._prefix + session_id)
if exists(session_file):
os.remove(session_file)
def remove_expires(self):
if not exists(self.host) or not isdir(self.host):return
now = utcnow()
for file in os.listdir(self.host):
if file.startswith(self._prefix):
session_file = join(self.host, file)
f = open(session_file, 'rb')
session = pickle.load(f)
f.close()
expires = session.get('__expires__', now)
if expires <= now:
os.remove(session_file)