Home  >  Article  >  Backend Development  >  Compare cookie and session instance operations in Django

Compare cookie and session instance operations in Django

巴扎黑
巴扎黑Original
2017-08-18 10:57:101332browse

This article introduces cookie and session operations in Django through sample code. Friends who need it can refer to it

Add cookies:


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})

Get cookie:


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

Delete cookie:


  Response.delete_cookie("username")

Add 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})

Get session:


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

Delete session:


##

del req.session['username']

The above is the detailed content of Compare cookie and session instance operations in Django. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn