python

超轻量级php框架startmvc

Django项目开发中cookies和session的常用操作分析

更新时间:2020-06-09 04:48:01 作者:startmvc
本文实例讲述了Django项目开发中cookies和session的常用操作。分享给大家供大家参考,具体如

本文实例讲述了Django项目开发中cookies和session的常用操作。分享给大家供大家参考,具体如下:

COOKIES操作

检查cookies是否存在:


request.COOKIES.has_key('<cookie_name>')

获取cookies:


request.COOKIES.get('visits', '1')
if 'last_visit' in request.COOKIES:
 request.COOKIES['last_visit']

设置cookies:


response.set_cookie('<cookie_name>', value)

SESSION操作

获取session:


fav_color = request.session.get('fav_color', 'red')
fav_color = request.session['fav_color']

设置session:


request.session['visits'] = visits

删除session:


del request.session['fav_color']

如果给出的key 在会话中不存在,将抛出 KeyError。

判断包含session:


'fav_color' in request.session

清除session数据库


python manage.py clearsessions

附:Django基于自定义cookies 的登录,注册,退出功能示例:


#注册
def regist(req):
 if req.method == 'POST':
 uf = UserForm(req.POST)
 if uf.is_valid():
 #获得表单数据
 username = uf.cleaned_data['username']
 password = uf.cleaned_data['password']
 #添加到数据库
 User.objects.create(username= username,password=password)
 return HttpResponse('regist success!!')
 else:
 uf = UserForm()
 return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req))
#登陆
def login(req):
 if req.method == 'POST':
 uf = UserForm(req.POST)
 if uf.is_valid():
 #获取表单用户密码
 username = uf.cleaned_data['username']
 password = uf.cleaned_data['password']
 #获取的表单数据与数据库进行比较
 user = User.objects.filter(username__exact = username,password__exact = password)
 if user:
 #比较成功,跳转index
 response = HttpResponseRedirect('/online/index/')
 #将username写入浏览器cookie,失效时间为3600
 response.set_cookie('username',username,3600)
 return response
 else:
 #比较失败,还在login
 return HttpResponseRedirect('/online/login/')
 else:
 uf = UserForm()
 return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))
#登陆成功
def index(req):
 username = req.COOKIES.get('username','')
 return render_to_response('index.html' ,{'username':username})
#退出
def logout(req):
 response = HttpResponse('logout !!')
 #清理cookie里保存username
 response.delete_cookie('username')
 return response

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

Django cookies session 常用操作