comparison MoinMoin/web/session.py @ 5802:dba48cb280f9

delete some code we had copied from werkzeug 0.6.1 while we bundled 0.5.1 (it is contained in the bundled werkzeug 0.8.1)
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Thu, 01 Dec 2011 02:05:15 +0100
parents af56baebf4d1
children
comparison
equal deleted inserted replaced
5801:8de563c487be 5802:dba48cb280f9
9 9
10 @copyright: 2008 MoinMoin:FlorianKrupicka, 10 @copyright: 2008 MoinMoin:FlorianKrupicka,
11 2009 MoinMoin:ThomasWaldmann 11 2009 MoinMoin:ThomasWaldmann
12 @license: GNU GPL, see COPYING for details. 12 @license: GNU GPL, see COPYING for details.
13 """ 13 """
14 import sys, os
15 from os import path
16 import time 14 import time
17 import tempfile 15
18 import re 16 from werkzeug.contrib.sessions import Session, FilesystemSessionStore
19 try:
20 from cPickle import load, dump, HIGHEST_PROTOCOL
21 except ImportError:
22 from pickle import load, dump, HIGHEST_PROTOCOL
23
24 from werkzeug.contrib.sessions import SessionStore, ModificationTrackingDict
25 17
26 from MoinMoin import config 18 from MoinMoin import config
27 from MoinMoin.util import filesys 19 from MoinMoin.util import filesys
28 rename = filesys.rename # use MoinMoin's rename until we have it in werkzeug 0.6.1
29 20
30 from MoinMoin import log 21 from MoinMoin import log
31 logging = log.getLogger(__name__) 22 logging = log.getLogger(__name__)
32
33
34 # start copy from werkzeug 0.6 - directly import this, if we require >= 0.6:
35
36 class Session(ModificationTrackingDict):
37 """Subclass of a dict that keeps track of direct object changes. Changes
38 in mutable structures are not tracked, for those you have to set
39 `modified` to `True` by hand.
40 """
41 __slots__ = ModificationTrackingDict.__slots__ + ('sid', 'new')
42
43 def __init__(self, data, sid, new=False):
44 ModificationTrackingDict.__init__(self, data)
45 self.sid = sid
46 self.new = new
47
48 @property
49 def should_save(self):
50 """True if the session should be saved.
51
52 .. versionchanged:: 0.6
53 By default the session is now only saved if the session is
54 modified, not if it is new like it was before.
55 """
56 return self.modified
57
58 def __repr__(self):
59 return '<%s %s %s%s>' % (
60 self.__class__.__name__,
61 self.sid,
62 dict.__repr__(self),
63 self.should_save and '*' or ''
64 )
65
66
67 #: used for temporary files by the filesystem session store
68 _fs_transaction_suffix = '.__wz_sess'
69
70 class FilesystemSessionStore(SessionStore):
71 """Simple example session store that saves sessions on the filesystem.
72 This store works best on POSIX systems and Windows Vista / Windows
73 Server 2008 and newer.
74
75 .. versionchanged:: 0.6
76 `renew_missing` was added. Previously this was considered `True`,
77 now the default changed to `False` and it can be explicitly
78 deactivated.
79
80 :param path: the path to the folder used for storing the sessions.
81 If not provided the default temporary directory is used.
82 :param filename_template: a string template used to give the session
83 a filename. ``%s`` is replaced with the
84 session id.
85 :param session_class: The session class to use. Defaults to
86 :class:`Session`.
87 :param renew_missing: set to `True` if you want the store to
88 give the user a new sid if the session was
89 not yet saved.
90 """
91
92 def __init__(self, path=None, filename_template='werkzeug_%s.sess',
93 session_class=None, renew_missing=False, mode=0644):
94 SessionStore.__init__(self, session_class)
95 if path is None:
96 path = tempfile.gettempdir()
97 self.path = path
98 if isinstance(filename_template, unicode):
99 filename_template = filename_template.encode(
100 sys.getfilesystemencoding() or 'utf-8')
101 assert not filename_template.endswith(_fs_transaction_suffix), \
102 'filename templates may not end with %s' % _fs_transaction_suffix
103 self.filename_template = filename_template
104 self.renew_missing = renew_missing
105 self.mode = mode
106
107 def get_session_filename(self, sid):
108 # out of the box, this should be a strict ASCII subset but
109 # you might reconfigure the session object to have a more
110 # arbitrary string.
111 if isinstance(sid, unicode):
112 sid = sid.encode(sys.getfilesystemencoding() or 'utf-8')
113 return path.join(self.path, self.filename_template % sid)
114
115 def save(self, session):
116 fn = self.get_session_filename(session.sid)
117 fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
118 dir=self.path)
119 f = os.fdopen(fd, 'wb')
120 try:
121 dump(dict(session), f, HIGHEST_PROTOCOL)
122 finally:
123 f.close()
124 try:
125 rename(tmp, fn)
126 os.chmod(fn, self.mode)
127 except (IOError, OSError):
128 pass
129
130 def delete(self, session):
131 fn = self.get_session_filename(session.sid)
132 try:
133 os.unlink(fn)
134 except OSError:
135 pass
136
137 def get(self, sid):
138 if not self.is_valid_key(sid):
139 return self.new()
140 try:
141 f = open(self.get_session_filename(sid), 'rb')
142 except IOError:
143 if self.renew_missing:
144 return self.new()
145 data = {}
146 else:
147 try:
148 try:
149 data = load(f)
150 except Exception:
151 data = {}
152 finally:
153 f.close()
154 return self.session_class(data, sid, False)
155
156 def list(self):
157 """Lists all sessions in the store.
158
159 .. versionadded:: 0.6
160 """
161 before, after = self.filename_template.split('%s', 1)
162 filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),
163 re.escape(after)))
164 result = []
165 for filename in os.listdir(self.path):
166 #: this is a session that is still being saved.
167 if filename.endswith(_fs_transaction_suffix):
168 continue
169 match = filename_re.match(filename)
170 if match is not None:
171 result.append(match.group(1))
172 return result
173
174 # end copy of werkzeug 0.6 code
175 23
176 24
177 class MoinSession(Session): 25 class MoinSession(Session):
178 """ Compatibility interface to Werkzeug-sessions for old Moin-code. 26 """ Compatibility interface to Werkzeug-sessions for old Moin-code.
179 27