1. 程式人生 > >Python學習---django知識補充之CBV

Python學習---django知識補充之CBV

patch python學習 時間 結果 borde pps pattern .sh display

Django知識補充之CBV

Django:

url --> def函數 FBV[function based view] 用函數和URL進行匹配

url --> 類 CBV[function based view] 用類和URL進行匹配

POSTMAN插件

http://blog.csdn.net/zzy1078689276/article/details/77528249

基於CBV的登錄實例:

settings.py

INSTALLED_APPS = [
   ...
 ‘app01‘,   # 註冊app
]
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)  # 現添加的配置,這裏是元組,註意逗號
TEMPLATES = [
   ...
   ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],
]

urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from app01 import views
urlpatterns = [
   # 基於CBV的登錄
 # url(r‘^login.html/‘, views.login),  # 原來基於函數
   url(r‘^login.html/‘, views.Login.as_view()), # 現在基於類名.as_view()
]

views.py

from django.shortcuts import render, redirect
from app01 import models
# 基於CBV的登錄,需要導入views
from django import views
class Login(views.View):
    # http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]
    def get(self, request, *args, **kwargs):
        print(request.method, ‘GGGGGGGGGGGG‘)
        message = ‘‘
        return render(request, ‘login.html‘, {‘message‘: message})  # 這裏是網頁html
    def post(self, request, *args, **kwargs):
        print(request.method, ‘OOOOOOOOOOOOO‘)
        username = request.POST.get("user")
        password = request.POST.get("pass")
        print(‘username: %s, password:%s‘ % (username, password))
         # obj = models.Administrator.objects.filter(username=username, password=password).count()
        # if obj:   從數據庫內取出數據,進行判斷也可以
        if username == ‘root‘ and password == ‘root‘:
            req = redirect(‘/index.html/‘)  # 接收redirect對象,# 這裏是瀏覽器路徑,偽靜態
            # req.set_cookie(‘username‘, username, max_age=10)  # 設置超時時間10s
            import datetime
            timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
            req.set_cookie(‘username‘, username, max_age=10, expires=timeout)
            # IE設置超時時間10s
            return req
            # return redirect(‘/index.html‘) # 與上面3行同,只是添加了Cookie
        else:
            message = ‘用戶名或密碼錯誤‘
            return render(request, ‘login.html‘, {‘message‘: message})  # 這裏是網頁html

templates/login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {# 偽靜態#}
    <form action="/login.html/" method="post">
        {% csrf_token %}   {# 為跨站請求 #}
        <div>
            <label for="user">用戶名</label>
            <input id="user" name="user" type="text">
        </div>
        <div>
            <label for="pass">密&nbsp;&nbsp;&nbsp;&nbsp;碼</label>
            <input id="pass" name="pass" type="password">
        </div>
        <div>
            <label></label>
            <input value="登錄" type="submit">
            <span style="color: red">{{ message }}</span>
        </div>
    </form>
</body>
</html>

templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <h2>hello, {{ username }}</h2>
</body>
</html>

頁面顯示:

技術分享圖片

CBV基於裝飾器的使用<一> ---基於Python舊方法

CBV基於裝飾器的使用<一> ---基於Python舊方法

裝飾器:函數執行之前/後可以增加擴展功能

有多個方法的時候,必須給每個方法添加裝飾器哈

CBV的反射原理

技術分享圖片

單一裝飾器

views.py

from django.shortcuts import render, redirect
from app01 import models
# 基於CBV的登錄,需要導入views
from django import views
from django.utils.decorators import method_decorator  # 導入裝飾器
# 基於CBV的裝飾器的使用
def outer(func):
    def inner(request, *args, **kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner

class Login(views.View):
    # http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]
    @method_decorator(outer)
    def get(self, request, *args, **kwargs):
        message = ‘‘
        return render(request, ‘login.html‘, {‘message‘: message})  # 這裏是網頁html

    @method_decorator(outer)
    def post(self, request, *args, **kwargs):
        username = request.POST.get("user")
        password = request.POST.get("pass")
        print(‘username: %s, password:%s‘ % (username, password))
        # obj = models.Administrator.objects.filter(username=username, password=password).count()
        # if obj:   從數據庫內取出數據,進行判斷也可以
        if username == ‘root‘ and password == ‘root‘:
            req = redirect(‘/index.html/‘)  # 接收redirect對象,# 這裏是瀏覽器路徑,偽靜態
            # req.set_cookie(‘username‘, username, max_age=10)  # 設置超時時間10s
            import datetime
            timeout = datetime.datetime.now() + datetime.timedelta(seconds=10)
            req.set_cookie(‘username‘, username, max_age=10, expires=timeout)
            # IE設置超時時間10s
            return req
            # return redirect(‘/index.html‘) # 與上面3行同,只是添加了Cookie
        else:
            message = ‘用戶名或密碼錯誤‘
            return render(request, ‘login.html‘, {‘message‘: message})  # 這裏是網頁html

CBV基於裝飾器的使用<二> --基於Django的dispatch[多個裝飾器]

CBV基於裝飾器的使用<二> --基於Django的dispatch[多個裝飾器]

如果對某一種請求做處理: 單一裝飾器

如果對所有的請求做處理: dispatch單一裝飾器

添加裝飾器有2中方法:

1.類上添加

2.方法上添加

技術分享圖片

自定義轉發dispatch函數

from django import views
from django.utils.decorators import method_decorator  # 導入裝飾器
class Login(views.View):
    # http_method_names = [‘get‘, ‘post‘, ‘put‘, ‘patch‘, ‘delete‘, ‘head‘, ‘options‘, ‘trace‘]
    # 自定義轉發器,URL進來都在此處進行URL轉發,我們可以有一些預操作[函數驗證可以放此處]
    def dispatch(self, request, *args, **kwargs):
        print(‘自定義dispatch: 前‘)
        # if request.method == ‘POST‘:
            # return HttpResponse("Good Bye")    # 預操作處理
        # 請求先到Login的dispatch,然後調用父類的dispatch,返回結果給了obj
        obj = super(Login, self).dispatch(request, *args, **kwargs)  # 自定義轉發且調用父類dispatch
        # 將父類的返回結果返回給界面,否則界面報錯
        print(‘自定義dispatch: 後‘)
        return obj

    def get(self, request, *args, **kwargs):
        message = ‘‘
        return render(request, ‘login.html‘, {‘message‘: message})  # 這裏是網頁html
        ...同上

技術分享圖片

Python學習---django知識補充之CBV