session.py 11 KB

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