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

时间:2022-05-26 13:22:09

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

COOKIES操作

检查cookies是否存在:

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

获取cookies:

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

设置cookies:

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

SESSION操作

获取session:

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

设置session:

?
1
request.session['visits'] = visits

删除session:

?
1
del request.session['fav_color']

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

判断包含session:

?
1
'fav_color' in request.session

清除session数据库

?
1
python manage.py clearsessions

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#注册
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程序设计有所帮助。

原文链接:https://blog.csdn.net/win_turn/article/details/52997641