欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django中的cookie与session操作实例代码

程序员文章站 2024-03-12 09:04:08
添加cookie: def login(req): if req.method=="post": uf = userinfoform(req.po...

添加cookie:

def login(req):
  if req.method=="post":
    uf = userinfoform(req.post)
    if uf.is_valid():
      username = uf.cleaned_data["username"]
      password = uf.cleaned_data["password"]
      print username,password
      users = userinfo.objects.filter(username=username,password=password)
      if users:
        response = httpresponseredirect("/index/")
        response.set_cookie("username",username,3600)
        return response
      else:
        return httpresponseredirect("/login")
      # return httpresponseredirect()
  else:
    uf = userinfoform()
  return render_to_response("login.html",{"uf":uf})

获得cookie:

def index(req):
  username = req.cookies.get("username","")return render_to_response("index.html",{"username":username})

删除cookie:

  response.delete_cookie("username")

添加session:

def sesion(req):
  if req.method == "post":
    uf = userinfoform(req.post)
    if uf.is_valid():
      username = uf.cleaned_data["username"]
      req.session["username"] = username
      return httpresponseredirect("/index/")
  else:
    uf = userinfoform()
  return render_to_response("loadfile.html",{"uf":uf})

获取session:

def index(req):
  username = req.session.get("username","")
  return render_to_response("index.html",{"username":username})

删除session:

del req.session['username']

总结

以上所述是小编给大家介绍的django中的cookie与session操作实例代码,希望对大家有所帮助