Bez popisu
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.4KB

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