会话(Session)用来在服务器端保存单个用户的会话状态,一般用于登录以后。会话ID可以通过cookie来传递给客户端,用于识别当前登录的用户。
参考:https://docs.djangoproject.com/en/dev/topics/http/sessions/
开启Session中间件
Session引擎
在View中操作Session对象
fav_color = request.session['fav_color']
request.session['fav_color'] = 'blue'
del request.session['fav_color']
'fav_color' in request.session
fav_color = request.session.get('fav_color', default='red')
fav_color = request.session.pop('fav_color')
request.session.set_expiry(300)
def login(request): m = Member.objects.get(username=request.POST['username']) if m.password == request.POST['password']: request.session['member_id'] = m.id return HttpResponse("You're logged in.") else: return HttpResponse("Your username and password didn't match.")
def post_comment(request, new_comment): if request.session.get('has_commented', False): return HttpResponse("You've already commented.") c = comments.Comment(comment=new_comment) c.save() request.session['has_commented'] = True return HttpResponse('Thanks for your comment!')
def logout(request): try: del request.session['member_id'] except KeyError: pass return HttpResponse("You're logged out.")
测试客户端是否支持cookie
def login(request): if request.method == 'POST': if request.session.test_cookie_worked(): request.session.delete_test_cookie() return HttpResponse("You're logged in.") else: return HttpResponse("Please enable cookies and try again.") request.session.set_test_cookie() return render_to_response('foo/login_form.html')
Django will only save session when the value under a key has been modified. When you write:
request.session['array'] = []
it means that the value is a reference to your array. Appending items to the array will not modify the value (the reference to array), thus django sees no reason to save the session.
There are 2 ways of fixing this:
1) Tell django to explicitly save the session:
request.session.modified = True
2) set the SESSION_SAVE_EVERY_REQUEST setting to True. Django will then save the session to the database on every single request