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

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

Python判断两个list是否是父子集关系的实例

list1 和list2 两个list , 想要得到list1是不是包含 list2 (是不是其子集 ) a = [1,2] b = [1,2,3] c = [0, 1]...

python多线程抽象编程模型详解

最近需要完成一个多线程下载的工具,对其中的多线程下载进行了一个抽象,可以对所有需要使用到多线程编程的地方统一使用这个模型来进行编写。 主要结构: 1、基于Queue标准库实现了一个类似线...

python实现广度优先搜索过程解析

广度优先搜索 适用范围: 无权重的图,与深度优先搜索相比,深度优先搜索法占内存少但速度较慢,广度优先搜索算法占内存多但速度较快 复杂度: 时间复杂度为O(V+E),V为顶点数,E为边...

将tensorflow.Variable中的某些元素取出组成一个新的矩阵示例

在神经网络计算过程中,经常会遇到需要将矩阵中的某些元素取出并且单独进行计算的步骤(例如MLE,Attention等操作)。那么在 tensorflow 的 Variable 类型中如何做...

python关于矩阵重复赋值覆盖问题的解决方法

本文实例讲述了python关于矩阵重复赋值覆盖问题的解决方法。分享给大家供大家参考,具体如下: import itertools import numpy as np comb =...