03: django Advanced articles

1.1 cookie

  1, cookie Introduction

      1. cookie essence is the client hard disk to store key-value pairs, the use of this feature can be used for user authentication

      2. For example: { "username": "dachengzi"} # url to access the information again will carry over

  2, the front end of cookie operation
      instructions: using the following method of operation must be introduced into the cookie jquery.cookie.js

      1. Get distal cookie value:  var .cookie V = $ ( 'per_page_count'); 

      2. The front end of the cookie value:  $ .cookie ( 'per_page_count', V); 

  3, back-end operations cookie

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

      1. Set rear cookie value:   response.set_cookie ( 'username', "zhangsan")

      2. After the rear end to the cookie value:  request.COOKIES.get ( 'username') 

  4, uses a cookie implement user login, logout  

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, = the max_age 10)         # Set Free 500s landing 
            return RES
         the else :
             return the render (Request, ' the login.html ' , { ' MSG ' : ' username or password ' }) 

DEF Zimbabwe Logout (REQ): 
    Response = the redirect ( ' / the Login / ' )
     # clean up the cookie saved username 
    response.delete_cookie ( ' username ' )
     return the 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

 

Guess you like

Origin www.cnblogs.com/xiaonq/p/10962188.html