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

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})  # 這里是網頁htmldef 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)  # 設置超時時間10simport datetimetimeout = datetime.datetime.now() + datetime.timedelta(seconds=10)req.set_cookie('username', username, max_age=10, expires=timeout)# IE設置超時時間10sreturn req# return redirect('/index.html') # 與上面3行同,只是添加了Cookieelse: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>

頁面顯示:

image

?

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

?

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

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

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

CBV的反射原理

image

單一裝飾器

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 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)  # 設置超時時間10simport datetimetimeout = datetime.datetime.now() + datetime.timedelta(seconds=10)req.set_cookie('username', username, max_age=10, expires=timeout)# IE設置超時時間10sreturn req# return redirect('/index.html') # 與上面3行同,只是添加了Cookieelse:message = '用戶名或密碼錯誤'return render(request, 'login.html', {'message': message})  # 這里是網頁html

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

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

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

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

添加裝飾器有2中方法:

??? 1.類上添加??

??? 2.方法上添加

image

自定義轉發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,返回結果給了objobj = super(Login, self).dispatch(request, *args, **kwargs)  # 自定義轉發且調用父類dispatch# 將父類的返回結果返回給界面,否則界面報錯print('自定義dispatch: 后')return objdef get(self, request, *args, **kwargs):message = ''return render(request, 'login.html', {'message': message})  # 這里是網頁html...同上

image

轉載于:https://www.cnblogs.com/ftl1012/p/9403851.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388961.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388961.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388961.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

「CH2101」可達性統計 解題報告

CH2101 可達性統計 描述 給定一張N個點M條邊的有向無環圖&#xff0c;分別統計從每個點出發能夠到達的點的數量。N,M≤30000。 輸入格式 第一行兩個整數N,M&#xff0c;接下來M行每行兩個整數x,y&#xff0c;表示從x到y的一條有向邊。 輸出格式 共N行&#xff0c;表示每個點能夠…

藍圖解鎖怎么用_[UE4藍圖][Materials]虛幻4中可互動的雪地材質完整實現(一)

不說廢話&#xff0c;先上個演示圖最終成果&#xff08;腳印&#xff0c;雪地可慢慢恢復&#xff0c;地形可控制&#xff09;主要原理&#xff08;白話文&#xff09;&#xff1a;假如你頭上是塊白色并且可以透視的平地&#xff0c;來了個非洲兄弟踩上面&#xff0c;你拿起單反…

數據預處理工具_數據預處理

數據預處理工具As the title states this is the last project from Udacity Nanodegree. The goal of this project is to analyze demographics data for customers of a mail-order sales company in Germany.如標題所示&#xff0c;這是Udacity Nanodegree的最后一個項目。…

這幾日英文大匯

int > 整數. 主要?用來進?行行數學運算 str > 字符串串, 可以保存少量量數據并進?行行相應的操作 bool>判斷真假, True, False list> 存儲?大量量數據.?用[ ]表?示 tuple> 元組, 不可以發?生改變 ?用( )表?示 dict>字典,保存鍵值對,?一樣可以…

在網上收集了一部分關于使用Google API進行手機定位的資料和大家分享

在網上收集了一部分關于使用Google API進行手機定位的資料和大家分享&#xff1a;關于基站定位方面的介紹&#xff1a;http://tech.c114.net/164/a140837.html開發方面的幫助&#xff1a;http://www.dotblogs.com.tw/kylin/archive/2009/08/09/9964.aspxhttp://code.google.com…

background圖片疊加_css怎么讓兩張圖片疊加,不用background只用img疊加

展開全部css層疊圖片代碼&#xff1a;//這個層為外面的父層&#xff0c;只需設置相對位置樣式即可//這個為里e69da5e887aa3231313335323631343130323136353331333431363030面要疊加的層&#xff0c;只需設置絕對樣式//這個為層里面的內容圖片//這個為父層內容或者&#xff1a;擴…

“入鄉隨俗,服務為主” 發明者量化兼容麥語言啦!

5年時光 我們裹挾前行。發明者量化從篳路藍縷到步履蹣跚&#xff0c;從以“區塊鏈資產交易”為陣地&#xff0c;再到以“內外盤商品期貨”為依托。再到今天全面兼容“麥語言”。每一步&#xff0c;我們始終都在為建立一個優秀的量化交易平臺而努力。 什么是麥語言&#xff1f; …

自考數據結構和數據結構導論_我跳過大學自學數據科學

自考數據結構和數據結構導論A few months back, I decided I wanted to learn data science. In order to do this, I skipped an entire semester of my data science major.幾個月前&#xff0c;我決定要學習數據科學。 為此&#xff0c; 我跳過了數據科學專業的整個學期。 …

爬取LeetCode題目——如何發送GraphQL Query獲取數據

前言 GraphQL 是一種用于 API 的查詢語言&#xff0c;是由 Facebook 開源的一種用于提供數據查詢服務的抽象框架。在服務端 API 開發中&#xff0c;很多時候定義一個接口返回的數據相對固定&#xff0c;因此要獲得更多信息或者只想得到某部分信息時&#xff0c;基于 RESTful AP…

python中的thread_Python中的thread

測試代碼import threadingimport timedef do_thread_test():print start thread time:, time.strftime(%H:%M:%S)time.sleep(5)print stop thread time:, time.strftime(%H:%M:%S)threads []for i in range(2):thread1 threading.Thread(targetdo_thread_test)thread1.setDae…

--附加數據庫失敗

--附加數據庫失敗1.產生失敗的原因比如有個數據庫&#xff0c;名叫HIMS,它的數據文件HIMS_Data.mdf和日志文件HIMS_Log.ldf,都放在路徑c:/Program Files/Microsoft SQL Server/MSSQL/data/下。但是這個數據庫天天跑日志&#xff0c;會產生上G的日志&#xff0c;現在通過企業管理…

十三、原生爬蟲實戰

一、簡單實例 1、需求&#xff1a;爬取熊貓直播某類主播人氣排行 2、了解網站結構 分類——英雄聯盟——"觀看人數" 3、找到有用的信息 二、整理爬蟲常規思路 1、使用工具chrome——F12——element——箭頭——定位目標元素 目標元素&#xff1a;主播名字&#xff0c…

歸一化 均值歸一化_歸一化折現累積收益

歸一化 均值歸一化Do you remember the awkward moment when someone you had a good conversation with forgets your name? In this day and age we have a new standard, an expectation. And when the expectation is not met the feeling is not far off being asked “w…

sqlserver垮庫查詢_Oracle和SQLServer中實現跨庫查詢

一、在SQLServer中連接另一個SQLServer庫數據在SQL中&#xff0c;要想在本地庫中查詢另一個數據庫中的數據表時&#xff0c;可以創建一個鏈接服務器&#xff1a;EXEC master.dbo.sp_addlinkedserver server N別名, srvproductN庫名,providerNSQLOLEDB, datasrcN服務器地址EXEC…

Angular2+ typescript 項目里面用require

在typescript里面怎么使用require方法呢&#xff1f; const jQuery require(jquery); const fip require( fonticonpicker/fonticonpicker )( jQuery ); 如果什么都不做&#xff0c;直接在項目里面使用&#xff0c;會得到以下錯誤&#xff1a; Cannot find name require 以下…

機器學習實踐三---神經網絡學習

Neural Networks 在這個練習中&#xff0c;將實現神經網絡BP算法,練習的內容是手寫數字識別。Visualizing the data 這次數據還是5000個樣本&#xff0c;每個樣本是一張20*20的灰度圖片fig, ax_array plt.subplots(nrows10, ncols10, figsize(6, 4))for row in range(10):fo…

Microsoft Expression Blend 2 密鑰,key

Microsoft Expression Blend 2 密鑰&#xff0c;key&#xff0c;序列TJ2R3-WHW22-B848T-B78YJ-HHJWJ號

ethereumjs/ethereumjs-common-3-test

查看test能夠讓你更好滴了解其API文檔的使用 ethereumjs-common/tests/chains.js const tape require(tape) const Common require(../index.js)tape([Common]: Initialization / Chain params, function (t) {t.test(Should initialize with chain provided, function (st) …

mysql修改_mysql修改表操作

一&#xff1a; 修改表信息1.修改表名alter table test_a rename to sys_app;2.修改表注釋alter table sys_application comment 系統信息表;二&#xff1a;修改字段信息1.修改字段類型和注釋alter table sys_application modify column app_name varchar(20) COMMENT 應用的名…

機器學習實踐四--正則化線性回歸 和 偏差vs方差

這次實踐的前半部分是&#xff0c;用水庫水位的變化&#xff0c;來預測大壩的出水量。 給數據集擬合一條直線&#xff0c;可能得到一個邏輯回歸擬合&#xff0c;但它并不能很好地擬合數據&#xff0c;這是高偏差&#xff08;high bias&#xff09;的情況&#xff0c;也稱為“欠…