下面是django使用session的例子,参考djangoBook:
def login(request): if request.method != 'POST': raise Http404('Only POSTs are allowed') try: m = Member.objects.get(username=request.POST['username']) if m.password == request.POST['password']: request.session['member_id'] = m.id return HttpResponseRedirect('/you-are-logged-in/') except Member.DoesNotExist: return HttpResponse("Your username and password didn't match.")
通过POST表单,提交username和password。
然后在Member模型中,查找是否匹配。若匹配,则对request.session看作字典赋值,就会建立起session。
下图是django session的处理流程:
我们主要看SessionMiddleware的实现:
class SessionMiddleware(object): def __init__(self): engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore
这是SessionMiddleware的初始化。从settings模块中读取SESSION_ENGINE的值,默认是'django.contrib.sessions.backends.db',采用数据库存储。还可以设置别的值,比如'django.contrib.sessions.backends.file','django.contrib.sessions.backends.cache'等等。
下面是处理客户端请求:
def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) request.session = self.SessionStore(session_key)
cookie里面会存settings.SESSION_COOKIE_NAME(默认为'sessionid')的值。
取出cookie中的值,然后根据session_key获取相应的session_data值。
SessionSrore类是一个包装成字典的类,负责session_data的存储和修改。
在看看如何在response更新session的:
def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie(settings.SESSION_COOKIE_NAME) else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: request.session.save() response.set_cookie(settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None) return response
这里分几种情况讨论:
如果session被清除了,那么客户端的cookie也应该要清除。通过response.delete_cookie( )方法清除。
如果session被修改,并且没有500error, 就会跟新客户端的cookie,通过response.set_cookie( )方法。