Personal wiki notebook (not under development)

Session_storage.py 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import cherrypy
  2. import cPickle as pickle
  3. from datetime import datetime
  4. class Session_storage( object ):
  5. """
  6. A CherryPy session storage class, originally based on CherryPy's PostgreSQLStorage. It assumes
  7. a table like this:
  8. create table session (
  9. id text,
  10. data text,
  11. expiration_time timestamp
  12. )
  13. It differs from PostgreSQLStorage in the following ways:
  14. * changes to the database are actually committed after they are made
  15. * a new cursor is created for each database access to prevent problems with multiple threads
  16. * a connection is requested from cherrypy.root.database instead of a session_filter.get_db method
  17. * __del__ is not implemented because it should not be relied upon
  18. * no locking is implemented
  19. """
  20. def __init__( self ):
  21. self.conn = cherrypy.root.database.get_connection()
  22. def load( self, id ):
  23. cursor = self.conn.cursor()
  24. # Select session data from table
  25. cursor.execute(
  26. 'select data, expiration_time from session where id=%s',
  27. (id,))
  28. rows = cursor.fetchall()
  29. if not rows:
  30. return None
  31. pickled_data, expiration_time = rows[0]
  32. # Unpickle data
  33. data = pickle.loads(pickled_data)
  34. return (data, expiration_time)
  35. def save( self, id, data, expiration_time ):
  36. cursor = self.conn.cursor()
  37. # Try to delete session if it was already there
  38. cursor.execute(
  39. 'delete from session where id=%s',
  40. (id,))
  41. # Pickle data
  42. pickled_data = pickle.dumps(data)
  43. # Insert new session data
  44. cursor.execute(
  45. 'insert into session (id, data, expiration_time) values (%s, %s, %s)',
  46. (id, pickled_data, expiration_time))
  47. self.conn.commit()
  48. def clean_up( self, sess ):
  49. cursor = self.conn.cursor()
  50. now = datetime.now()
  51. cursor.execute(
  52. 'select data from session where expiration_time < %s',
  53. (now,))
  54. rows = cursor.fetchall()
  55. for row in rows:
  56. sess.on_delete_session(row[0])
  57. cursor.execute(
  58. 'delete from session where expiration_time < %s',
  59. (now,))
  60. self.conn.commit()
  61. def acquire_lock( self ):
  62. raise NotImplemented()
  63. def release_lock( self ):
  64. raise NotImplemented()