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

來源:互聯網
上載者:User

標籤:自訂   ora   splay   csr   install   model   pass   使用者名稱   port   

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 adminfrom django.urls import pathfrom django.conf.urls import url, includefrom app01 import viewsurlpatterns = [   # 基於CBV的登入 # url(r‘^login.html/‘, views.login),  # 原來基於函數   url(r‘^login.html/‘, views.Login.as_view()), # 現在基於類名.as_view()]

views.py

from django.shortcuts import render, redirectfrom app01 import models# 基於CBV的登入,需要匯入viewsfrom django import viewsclass 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, redirectfrom app01 import models# 基於CBV的登入,需要匯入viewsfrom django import viewsfrom django.utils.decorators import method_decorator  # 匯入裝飾器# 基於CBV的裝飾器的使用def outer(func):    def inner(request, *args, **kwargs):        print(request.method)        return func(request, *args, **kwargs)    return innerclass 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 viewsfrom 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.