Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

run.py 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 = [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. expiration_timestamp = os.path.join(session_files_path, session_file).st_mtime + \
  19. SESSION_EXPIRATION_LIMIT
  20. if timestamp_now > expiration_timestamp:
  21. os.unlink(os.path.join(session_files_path, session_file))
  22. # TODO Déplacer dans une module "sessions.py"
  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)