03: django进阶篇

1.1 cookie

  1、cookie简介

      1. cookie实质就是客户端硬盘中存放的键值对,利用这个特性可以用来做用户验证

      2. 比如:{“username”: “dachengzi”} #再次访问url就会携带这些信息过来

  2、前端操作cookie
      说明: 使用下面方法操cookie必须先引入jquery.cookie.js

      1. 前端获取cookie值:  var v = $.cookie('per_page_count');

      2. 前端设置cookie值:  $.cookie('per_page_count',v);

  3、后端操作cookie

      说明: response = HttpResponse(...)  或  response = render(request, ...)

      1. 后端设置cookie值:  response.set_cookie('username',"zhangsan")

      2. 后端后去cookie值:  request.COOKIES.get('username')

  4、使用cookie实现用户登录、注销  

from django.contrib import admin
from django.urls import path,re_path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'login/$',views.login),
    re_path(r'index/$',views.index),
    re_path(r'logout/$',views.logout),
]
urls.py
from django.shortcuts import render,HttpResponse,redirect

def index(request):
    username = request.COOKIES.get('username')        # 获取cookie
    if not username:
        return redirect('/login/')
    return HttpResponse(username)

def login(request):
    if request.method == "GET":
        return render(request,'login.html',{'msg':''})
    if request.method == "POST":
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        print(u,p)
        if u == 'tom' and p == '123':
            res = redirect('/index/')
            res.set_cookie('username',u ,max_age=10)        # 设置500s免登陆
            return res
        else:
            return render(request,'login.html', {'msg':'用户名或密码错误'})

def logout(req):
    response = redirect('/login/')
    #清理cookie里保存username
    response.delete_cookie('username')
    return response
views.py
    <form action="/login/" method="POST">
        <input type="text" name="username" placeholder="用户名">
        <input type="text" name="pwd" placeholder="密码">
        <input type="submit" value="提交">
        <p>{{ msg }}</p>
    </form>
login.html

 

posted @ 2019-06-02 10:42  不做大哥好多年  阅读(233)  评论(0编辑  收藏  举报