Django session
在视图中使用session
request.session可以在视图中的任何地方使用,它类似python中的字典
session的默认有效时间是两周,可以在settings.py中修改默认值
#创建或修改 session:
request.session[key] = value
#获取 session
request.session.get[key,default=None]
#删除 session
delete request.session.get[key] # 不存在时报错
session 例子
比如写一个不让用户看到的两次评论的应用
from django.http import HttpResponse
def post_comment(request,new_comment):
if request.session.get('has_comment',False):
return HttpResponse('You've already commented.')
c = comment.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
一个简化的登录认证:
def login(request):
m = Menber.objects.get(username=request.POST['username'])
if m.password==request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You've logged in.")
else:
return HttpResponse("Your username and password didn't match.")
def logout(request):
try:
del request.session['member.id']
except KeyError:
pass
return HttpResponse("You've logged out.")