session.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
  2. # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
  3. """
  4. Creates a session object in your WSGI environment.
  5. Use like:
  6. ..code-block:: Python
  7. environ['paste.session.factory']()
  8. This will return a dictionary. The contents of this dictionary will
  9. be saved to disk when the request is completed. The session will be
  10. created when you first fetch the session dictionary, and a cookie will
  11. be sent in that case. There's current no way to use sessions without
  12. cookies, and there's no way to delete a session except to clear its
  13. data.
  14. @@: This doesn't do any locking, and may cause problems when a single
  15. session is accessed concurrently. Also, it loads and saves the
  16. session for each request, with no caching. Also, sessions aren't
  17. expired.
  18. """
  19. from Cookie import SimpleCookie
  20. import time
  21. import random
  22. import os
  23. import datetime
  24. import threading
  25. import tempfile
  26. try:
  27. import cPickle
  28. except ImportError:
  29. import pickle as cPickle
  30. try:
  31. from hashlib import md5
  32. except ImportError:
  33. from md5 import md5
  34. from paste import wsgilib
  35. from paste import request
  36. class SessionMiddleware(object):
  37. def __init__(self, application, global_conf=None, **factory_kw):
  38. self.application = application
  39. self.factory_kw = factory_kw
  40. def __call__(self, environ, start_response):
  41. session_factory = SessionFactory(environ, **self.factory_kw)
  42. environ['paste.session.factory'] = session_factory
  43. remember_headers = []
  44. def session_start_response(status, headers, exc_info=None):
  45. if not session_factory.created:
  46. remember_headers[:] = [status, headers]
  47. return start_response(status, headers)
  48. headers.append(session_factory.set_cookie_header())
  49. return start_response(status, headers, exc_info)
  50. app_iter = self.application(environ, session_start_response)
  51. def start():
  52. if session_factory.created and remember_headers:
  53. # Tricky bastard used the session after start_response
  54. status, headers = remember_headers
  55. headers.append(session_factory.set_cookie_header())
  56. exc = ValueError(
  57. "You cannot get the session after content from the "
  58. "app_iter has been returned")
  59. start_response(status, headers, (exc.__class__, exc, None))
  60. def close():
  61. if session_factory.used:
  62. session_factory.close()
  63. return wsgilib.add_start_close(app_iter, start, close)
  64. class SessionFactory(object):
  65. def __init__(self, environ, cookie_name='_SID_',
  66. session_class=None,
  67. session_expiration=60*12, # in minutes
  68. **session_class_kw):
  69. self.created = False
  70. self.used = False
  71. self.environ = environ
  72. self.cookie_name = cookie_name
  73. self.session = None
  74. self.session_class = session_class or FileSession
  75. self.session_class_kw = session_class_kw
  76. self.expiration = session_expiration
  77. def __call__(self):
  78. self.used = True
  79. if self.session is not None:
  80. return self.session.data()
  81. cookies = request.get_cookies(self.environ)
  82. session = None
  83. if cookies.has_key(self.cookie_name):
  84. self.sid = cookies[self.cookie_name].value
  85. try:
  86. session = self.session_class(self.sid, create=False,
  87. **self.session_class_kw)
  88. except KeyError:
  89. # Invalid SID
  90. pass
  91. if session is None:
  92. self.created = True
  93. self.sid = self.make_sid()
  94. session = self.session_class(self.sid, create=True,
  95. **self.session_class_kw)
  96. session.clean_up()
  97. self.session = session
  98. return session.data()
  99. def has_session(self):
  100. if self.session is not None:
  101. return True
  102. cookies = request.get_cookies(self.environ)
  103. if cookies.has_key(self.cookie_name):
  104. return True
  105. return False
  106. def make_sid(self):
  107. # @@: need better algorithm
  108. return (''.join(['%02d' % x for x in time.localtime(time.time())[:6]])
  109. + '-' + self.unique_id())
  110. def unique_id(self, for_object=None):
  111. """
  112. Generates an opaque, identifier string that is practically
  113. guaranteed to be unique. If an object is passed, then its
  114. id() is incorporated into the generation. Relies on md5 and
  115. returns a 32 character long string.
  116. """
  117. r = [time.time(), random.random()]
  118. if hasattr(os, 'times'):
  119. r.append(os.times())
  120. if for_object is not None:
  121. r.append(id(for_object))
  122. md5_hash = md5(str(r))
  123. try:
  124. return md5_hash.hexdigest()
  125. except AttributeError:
  126. # Older versions of Python didn't have hexdigest, so we'll
  127. # do it manually
  128. hexdigest = []
  129. for char in md5_hash.digest():
  130. hexdigest.append('%02x' % ord(char))
  131. return ''.join(hexdigest)
  132. def set_cookie_header(self):
  133. c = SimpleCookie()
  134. c[self.cookie_name] = self.sid
  135. c[self.cookie_name]['path'] = '/'
  136. gmt_expiration_time = time.gmtime(time.time() + (self.expiration * 60))
  137. c[self.cookie_name]['expires'] = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", gmt_expiration_time)
  138. name, value = str(c).split(': ', 1)
  139. return (name, value)
  140. def close(self):
  141. if self.session is not None:
  142. self.session.close()
  143. last_cleanup = None
  144. cleaning_up = False
  145. cleanup_cycle = datetime.timedelta(seconds=15*60) #15 min
  146. class FileSession(object):
  147. def __init__(self, sid, create=False, session_file_path=tempfile.gettempdir(),
  148. chmod=None,
  149. expiration=2880, # in minutes: 48 hours
  150. ):
  151. if chmod and isinstance(chmod, basestring):
  152. chmod = int(chmod, 8)
  153. self.chmod = chmod
  154. if not sid:
  155. # Invalid...
  156. raise KeyError
  157. self.session_file_path = session_file_path
  158. self.sid = sid
  159. if not create:
  160. if not os.path.exists(self.filename()):
  161. raise KeyError
  162. self._data = None
  163. self.expiration = expiration
  164. def filename(self):
  165. return os.path.join(self.session_file_path, self.sid)
  166. def data(self):
  167. if self._data is not None:
  168. return self._data
  169. if os.path.exists(self.filename()):
  170. f = open(self.filename(), 'rb')
  171. self._data = cPickle.load(f)
  172. f.close()
  173. else:
  174. self._data = {}
  175. return self._data
  176. def close(self):
  177. if self._data is not None:
  178. filename = self.filename()
  179. exists = os.path.exists(filename)
  180. if not self._data:
  181. if exists:
  182. os.unlink(filename)
  183. else:
  184. f = open(filename, 'wb')
  185. cPickle.dump(self._data, f)
  186. f.close()
  187. if not exists and self.chmod:
  188. os.chmod(filename, self.chmod)
  189. def _clean_up(self):
  190. global cleaning_up
  191. try:
  192. exp_time = datetime.timedelta(seconds=self.expiration*60)
  193. now = datetime.datetime.now()
  194. #Open every session and check that it isn't too old
  195. for root, dirs, files in os.walk(self.session_file_path):
  196. for f in files:
  197. self._clean_up_file(f, exp_time=exp_time, now=now)
  198. finally:
  199. cleaning_up = False
  200. def _clean_up_file(self, f, exp_time, now):
  201. t = f.split("-")
  202. if len(t) != 2:
  203. return
  204. t = t[0]
  205. try:
  206. sess_time = datetime.datetime(
  207. int(t[0:4]),
  208. int(t[4:6]),
  209. int(t[6:8]),
  210. int(t[8:10]),
  211. int(t[10:12]),
  212. int(t[12:14]))
  213. except ValueError:
  214. # Probably not a session file at all
  215. return
  216. if sess_time + exp_time < now:
  217. os.remove(os.path.join(self.session_file_path, f))
  218. def clean_up(self):
  219. global last_cleanup, cleanup_cycle, cleaning_up
  220. now = datetime.datetime.now()
  221. if cleaning_up:
  222. return
  223. if not last_cleanup or last_cleanup + cleanup_cycle < now:
  224. if not cleaning_up:
  225. cleaning_up = True
  226. try:
  227. last_cleanup = now
  228. t = threading.Thread(target=self._clean_up)
  229. t.start()
  230. except:
  231. # Normally _clean_up should set cleaning_up
  232. # to false, but if something goes wrong starting
  233. # it...
  234. cleaning_up = False
  235. raise
  236. class _NoDefault(object):
  237. def __repr__(self):
  238. return '<dynamic default>'
  239. NoDefault = _NoDefault()
  240. def make_session_middleware(
  241. app, global_conf,
  242. session_expiration=NoDefault,
  243. expiration=NoDefault,
  244. cookie_name=NoDefault,
  245. session_file_path=NoDefault,
  246. chmod=NoDefault):
  247. """
  248. Adds a middleware that handles sessions for your applications.
  249. The session is a peristent dictionary. To get this dictionary
  250. in your application, use ``environ['paste.session.factory']()``
  251. which returns this persistent dictionary.
  252. Configuration:
  253. session_expiration:
  254. The time each session lives, in minutes. This controls
  255. the cookie expiration. Default 12 hours.
  256. expiration:
  257. The time each session lives on disk. Old sessions are
  258. culled from disk based on this. Default 48 hours.
  259. cookie_name:
  260. The cookie name used to track the session. Use different
  261. names to avoid session clashes.
  262. session_file_path:
  263. Sessions are put in this location, default /tmp.
  264. chmod:
  265. The octal chmod you want to apply to new sessions (e.g., 660
  266. to make the sessions group readable/writable)
  267. Each of these also takes from the global configuration. cookie_name
  268. and chmod take from session_cookie_name and session_chmod
  269. """
  270. if session_expiration is NoDefault:
  271. session_expiration = global_conf.get('session_expiration', 60*12)
  272. session_expiration = int(session_expiration)
  273. if expiration is NoDefault:
  274. expiration = global_conf.get('expiration', 60*48)
  275. expiration = int(expiration)
  276. if cookie_name is NoDefault:
  277. cookie_name = global_conf.get('session_cookie_name', '_SID_')
  278. if session_file_path is NoDefault:
  279. session_file_path = global_conf.get('session_file_path', '/tmp')
  280. if chmod is NoDefault:
  281. chmod = global_conf.get('session_chmod', None)
  282. return SessionMiddleware(
  283. app, session_expiration=session_expiration,
  284. expiration=expiration, cookie_name=cookie_name,
  285. session_file_path=session_file_path, chmod=chmod)