3 from django
.conf
import settings
4 from django
.utils
.cache
import patch_vary_headers
5 from django
.utils
.http
import cookie_date
7 class SessionMiddleware(object):
8 def process_request(self
, request
):
9 engine
= __import__(settings
.SESSION_ENGINE
, {}, {}, [''])
10 session_key
= request
.COOKIES
.get(settings
.SESSION_COOKIE_NAME
, None)
11 request
.session
= engine
.SessionStore(session_key
)
13 def process_response(self
, request
, response
):
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.
19 accessed
= request
.session
.accessed
20 modified
= request
.session
.modified
21 except AttributeError:
25 patch_vary_headers(response
, ('Cookie',))
26 if modified
or settings
.SESSION_SAVE_EVERY_REQUEST
:
27 if request
.session
.get_expire_at_browser_close():
31 max_age
= request
.session
.get_expiry_age()
32 expires_time
= time
.time() + max_age
33 expires
= cookie_date(expires_time
)
34 # Save the session data and refresh the client cookie.
35 request
.session
.save()
36 response
.set_cookie(settings
.SESSION_COOKIE_NAME
,
37 request
.session
.session_key
, max_age
=max_age
,
38 expires
=expires
, domain
=settings
.SESSION_COOKIE_DOMAIN
,
39 path
=settings
.SESSION_COOKIE_PATH
,
40 secure
=settings
.SESSION_COOKIE_SECURE
or None)