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.
 
 
 
 

58 lines
2.6 KiB

  1. import time
  2. from importlib import import_module
  3. from django.conf import settings
  4. from django.utils.cache import patch_vary_headers
  5. from django.utils.http import cookie_date
  6. class SessionMiddleware(object):
  7. def __init__(self):
  8. engine = import_module(settings.SESSION_ENGINE)
  9. self.SessionStore = engine.SessionStore
  10. def process_request(self, request):
  11. session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
  12. request.session = self.SessionStore(session_key)
  13. def process_response(self, request, response):
  14. """
  15. If request.session was modified, or if the configuration is to save the
  16. session every time, save the changes and set a session cookie or delete
  17. the session cookie if the session has been emptied.
  18. """
  19. try:
  20. accessed = request.session.accessed
  21. modified = request.session.modified
  22. empty = request.session.is_empty()
  23. except AttributeError:
  24. pass
  25. else:
  26. # First check if we need to delete this cookie.
  27. # The session should be deleted only if the session is entirely empty
  28. if settings.SESSION_COOKIE_NAME in request.COOKIES and empty:
  29. response.delete_cookie(settings.SESSION_COOKIE_NAME,
  30. domain=settings.SESSION_COOKIE_DOMAIN)
  31. else:
  32. if accessed:
  33. patch_vary_headers(response, ('Cookie',))
  34. if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty:
  35. if request.session.get_expire_at_browser_close():
  36. max_age = None
  37. expires = None
  38. else:
  39. max_age = request.session.get_expiry_age()
  40. expires_time = time.time() + max_age
  41. expires = cookie_date(expires_time)
  42. # Save the session data and refresh the client cookie.
  43. # Skip session save for 500 responses, refs #3881.
  44. if response.status_code != 500:
  45. request.session.save()
  46. response.set_cookie(settings.SESSION_COOKIE_NAME,
  47. request.session.session_key, max_age=max_age,
  48. expires=expires, domain=settings.SESSION_COOKIE_DOMAIN,
  49. path=settings.SESSION_COOKIE_PATH,
  50. secure=settings.SESSION_COOKIE_SECURE or None,
  51. httponly=settings.SESSION_COOKIE_HTTPONLY or None)
  52. return response