No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

run.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # -*- coding: utf-8 -*-
  2. import os
  3. from werkzeug.contrib.sessions import FilesystemSessionStore
  4. from lodel.interface.web.router import get_controller
  5. from lodel.interface.web.lodelrequest import LodelRequest
  6. from lodel.utils.datetime import get_utc_timestamp
  7. # TODO Déplacer ces trois paramètres dans les settings
  8. SESSION_FILES_TEMPLATE = 'lodel_%s.sess'
  9. SESSION_FILES_BASE_DIR = 'tmp/sessions'
  10. SESSION_EXPIRATION_LIMIT = 900 # 15 min
  11. session_store = FilesystemSessionStore(path=SESSION_FILES_BASE_DIR, filename_template=SESSION_FILES_TEMPLATE)
  12. # TODO déplacer dans un module "sessions.py"
  13. def delete_old_session_files(timestamp_now):
  14. session_files_path = os.path.abspath(session_store.path)
  15. session_files = [os.path.join(session_files_path, file_object) for file_object in os.listdir(session_files_path)
  16. if os.path.isfile(os.path.join(session_files_path, file_object))]
  17. for session_file in session_files:
  18. last_modified = os.stat(session_file).st_mtime
  19. expiration_timestamp = last_modified + SESSION_EXPIRATION_LIMIT
  20. if timestamp_now > expiration_timestamp:
  21. os.unlink(session_file)
  22. def is_session_file_expired(timestamp_now, sid):
  23. session_file = session_store.get_session_filename(sid)
  24. expiration_timestamp = os.stat(session_file).st_mtime + SESSION_EXPIRATION_LIMIT
  25. if timestamp_now < expiration_timestamp:
  26. return False
  27. return True
  28. # WSGI Application
  29. def application(env, start_response):
  30. current_timestamp = get_utc_timestamp()
  31. delete_old_session_files(current_timestamp)
  32. request = LodelRequest(env)
  33. sid = request.cookies.get('sid')
  34. if sid is None or sid not in session_store.list():
  35. request.session = session_store.new()
  36. request.session['last_accessed'] = current_timestamp
  37. else:
  38. request.session = session_store.get(sid)
  39. if is_session_file_expired(current_timestamp, sid):
  40. session_store.delete(request.session)
  41. request.session = session_store.new()
  42. request.session['user_context'] = None
  43. request.session['last_accessed'] = current_timestamp
  44. controller = get_controller(request)
  45. response = controller(request)
  46. if request.session.should_save:
  47. session_store.save(request.session)
  48. response.set_cookie('sid', request.session.sid)
  49. return response(env, start_response)