最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Django中間件的5種自定義方法

 更新時(shí)間:2018年07月26日 09:21:19   作者:不_一  
這篇文章主要介紹了詳解Django中間件的5種自定義方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

Django中間件

在http請(qǐng)求 到達(dá)視圖函數(shù)之前 和視圖函數(shù)return之后,django會(huì)根據(jù)自己的規(guī)則在合適的時(shí)機(jī)執(zhí)行中間件中相應(yīng)的方法。

中間件的執(zhí)行流程

1、執(zhí)行完所有的request方法 到達(dá)視圖函數(shù)。

2、執(zhí)行中間件的其他方法

3、經(jīng)過所有response方法 返回客戶端。

注意:如果在其中1個(gè)中間件里 request方法里 return了值,就會(huì)執(zhí)行當(dāng)前中間件的response方法,返回給用戶 然后 報(bào)錯(cuò)。。不會(huì)再執(zhí)行下一個(gè)中間件。

自定義中間件

1.在project下隨便創(chuàng)建一個(gè)py文件

from django.utils.deprecation import MiddlewareMixin
class Middle1(MiddlewareMixin):
 def process_request(self,request):
  print("來了")
 def process_response(self, request,response):
  print('走了')

2、在setings文件中 注冊(cè)這個(gè) py文件

django項(xiàng)目的settings模塊中,有一個(gè) MIDDLEWARE_CLASSES變量,其中每一個(gè)元素就是一個(gè)中間件

MIDDLEWARE = [
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'M1.Middle1',
]

執(zhí)行結(jié)果

為啥報(bào)錯(cuò)了呢?

因?yàn)?自定義的中間件response方法沒有return,交給下一個(gè)中間件,導(dǎo)致http請(qǐng)求中斷了!??!

注意自定義的中間件request 方法不要return 因?yàn)榉祷刂抵虚g件不再往下執(zhí)行,導(dǎo)致 http請(qǐng)求到達(dá)不了視圖層,因?yàn)閞equest在視圖之前執(zhí)行!

from django.utils.deprecation import MiddlewareMixin
class Middle1(MiddlewareMixin):
 def process_request(self,request):
  print("來了") #不用return Django內(nèi)部自動(dòng)幫我們傳遞
 def process_response(self, request,response):
  print('走了')
  return response #執(zhí)行完了這個(gè)中間件一定要 傳遞給下一個(gè)中間件

中間件(類)中5種方法

中間件中可以定義5個(gè)方法,分別是:

  • process_request(self,request)
  • process_view(self, request, callback, callback_args, callback_kwargs)
  • process_template_response(self,request,response)
  • process_exception(self, request, exception)
  • process_response(self, request, response

1、 process_view(self, request, callback, callback_args, callback_kwargs)方法介紹

(1)執(zhí)行完所有中間件的request方法‘

(2)url匹配成功

(3)拿到 視圖函數(shù)的名稱、參數(shù),(注意不執(zhí)行) 再執(zhí)行process_view()方法

(4)最后去執(zhí)行視圖函數(shù)

玩法1(常規(guī))

from django.utils.deprecation import MiddlewareMixin


class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request') 

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")
  
 def process_response(self, request, response):
  print('M1.response')
  return response 



class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request') 

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")
 
 def process_response(self, request, response):
  print('M2.response')
  return response

執(zhí)行結(jié)果

玩法2

既然 process_view 拿到視圖函數(shù)的名稱、參數(shù),(不執(zhí)行) 再執(zhí)行process_view()方法,最后才去執(zhí)行視圖函數(shù)!

那可以在 執(zhí)行process_view環(huán)節(jié)直接 把函數(shù)執(zhí)行返回嗎?

from django.utils.deprecation import MiddlewareMixin
class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request')
     # callback視圖函數(shù)名稱 callback_args,callback_kwargs 視圖函數(shù)執(zhí)行所需的參數(shù)
 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")
  response=callback(request,*callback_args,**callback_kwargs)
  return response
 def process_response(self, request, response):
  print('M1.response')
  return response

class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request') 

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")
 def process_response(self, request, response):
  print('M2.response')
  return response

執(zhí)行結(jié)果

結(jié)論:

如果process_view函數(shù)有返回值,跳轉(zhuǎn)到最后一個(gè)中間件, 執(zhí)行最后一個(gè)中間件的response方法,逐步返回。

和 process_request方法不一樣哦! request方法在當(dāng)前中間件的response方法返回。

2、process_exception(self, request, exception)方法

from django.utils.deprecation import MiddlewareMixin


class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request')
  
 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")

 def process_response(self, request, response):
  print('M1.response')
  return response

 def process_exception(self, request,exception):
  print('M1的process_exception')


class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request') 

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")

 def process_response(self, request, response):
  print('M2.response')
  return response

 def process_exception(self, request, exception):
  print('M2的process_exception')

我去 加了process_exception方法 咋啥也沒執(zhí)行呢??。≡瓉硎莗rocess_exception默認(rèn)不執(zhí)行?。?!

大爺?shù)?原來process_exception方法在 視圖函數(shù)執(zhí)行出錯(cuò)的時(shí)候才會(huì)執(zhí)行

M1.request
M2.request
M1.process_view
M2.process_view
執(zhí)行index
M2的process_exception
M1的process_exception
Internal Server Error: /index/
Traceback (most recent call last):
 File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
 response = get_response(request)
 File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
 response = self.process_exception_by_middleware(e, request)
 File "C:\Users\Administrator\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
 File "F:\untitled1\app01\views.py", line 7, in index
 int("ok")
ValueError: invalid literal for int() with base 10: 'ok'
M2.response
M1.response
[03/Jul/2017 16:43:59] "GET /index/ HTTP/1.1" 500 62663

1、執(zhí)行完所有 request 方法

2、執(zhí)行 所有 process_view方法

3、如果視圖函數(shù)出錯(cuò),執(zhí)行process_exception(最終response,process_exception的return值)

如果process_exception 方法有了 返回值 就不再執(zhí)行 其他中間件的 process_exception,直接執(zhí)行response方法響應(yīng)

4.執(zhí)行所有response方法

5.最后返回process_exception的返回值

M1.request
M2.request
M1.process_view
M2.process_view
執(zhí)行index
M2的process_exception (有了return值,直接執(zhí)行response)
M2.response
M1.response

process_exception的應(yīng)用

在視圖函數(shù)執(zhí)行出錯(cuò)時(shí),返回錯(cuò)誤信息。這樣頁面就不會(huì) 報(bào)錯(cuò)了!

class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")

 def process_response(self, request, response):
  print('M1.response')
  return response

 def process_exception(self, request,exception):
  print('M1的process_exception')


class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")

 def process_response(self, request, response):
  print('M2.response')
  return response

 def process_exception(self, request, exception):
  print('M2的process_exception')
  return HttpResponse('出錯(cuò)了兄弟?。?!')

3、process_template_response()

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")

 def process_response(self, request, response):
  print('M1.response')
  return response


 def process_exception(self, request,exception):
  print('M1的process_exception')


class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")

 def process_response(self, request, response):
  print('M2.response')
  return response

 def process_exception(self, request, exception):
  print('M2的process_exception')

 def process_template_response(self,request,response):
  print('M2process_template_response')
  return response

process_template_response()默認(rèn)不執(zhí)行

rocess_template_response()特性

只有在視圖函數(shù)的返回對(duì)象中有render方法才會(huì)執(zhí)行!

并把對(duì)象的render方法的返回值返回給用戶(注意不返回視圖函數(shù)的return的結(jié)果了,而是返回視圖函數(shù) return值(對(duì)象)的render方法)

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse


class M1(MiddlewareMixin):
 def process_request(self, request):
  print('M1.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M1.process_view")

 def process_response(self, request, response):
  print('M1.response')
  return response


 def process_exception(self, request,exception):
  print('M1的process_exception')


class M2(MiddlewareMixin):
 def process_request(self, request):
  print('M2.request')

 def process_view(self, request,callback,callback_args,callback_kwargs ):
  print("M2.process_view")

 def process_response(self, request, response):
  print('M2.response')
  return response

 def process_exception(self, request, exception):
  print('M2的process_exception')

 def process_template_response(self,request,response): #如果視圖函數(shù)中的返回值 中有render方法,才會(huì)執(zhí)行 process_template_response
  print('M2process_template_response')
  return response

視圖函數(shù)

from django.shortcuts import render,HttpResponse

# Create your views here.
class Foo():
 def __init__(self,requ):
  self.req=requ
 def render(self):
  return HttpResponse('OKKKK')

def index(request):
 print("執(zhí)行index")
 obj=Foo(request)
 return obj

執(zhí)行結(jié)果

應(yīng)用:

既然process_template_respnse,不返回視圖函數(shù)的return的結(jié)果,而是返回視圖函數(shù) return值(對(duì)象)的render方法;(多加了一個(gè)環(huán)節(jié))

就可以在 這個(gè)視圖函數(shù)返回對(duì)象的 render方法里,做返回值的二次加工了!多加工幾個(gè),視圖函數(shù)就可以隨便使用了!

(好比 噴霧器有了多個(gè)噴頭,換不同的噴頭噴出不同水,返回值就可以也組件化了)

from django.shortcuts import render,HttpResponse

# Create your views here.
class Dict(): #對(duì)視圖函數(shù)返回值做二次封裝 ??!
 def __init__(self,requ,msg):
  self.req=requ 
  self.msg=msg
 def render(self):
  a=self.msg #在render方法里面 把視圖函數(shù)的 返回值 制作成字典 、列表等。。。 
     # 如果新增了其他 一個(gè)視圖函數(shù)直接,return對(duì)象 即可!不用每個(gè)視圖函數(shù)都寫 制作字典 列表 拼接的邏輯了
  return HttpResponse(a) #

def index(request):
 print("執(zhí)行index")
 obj=Dict(request,"vv")
 return obj

中間件應(yīng)用場(chǎng)景

由于中間件工作在 視圖函數(shù)執(zhí)行前、執(zhí)行后(像不像所有視圖函數(shù)的裝飾器?。┻m合所有的請(qǐng)求/一部分請(qǐng)求做批量處理

1、做IP限制

放在 中間件類的列表中,阻止某些IP訪問了;

2、URL訪問過濾

如果用戶訪問的是login視圖(放過)

如果訪問其他視圖(需要檢測(cè)是不是有session已經(jīng)有了放行,沒有返回login),這樣就省得在 多個(gè)視圖函數(shù)上寫裝飾器了!

3、緩存(還記得CDN嗎?)

客戶端請(qǐng)求來了,中間件去緩存看看有沒有數(shù)據(jù),有直接返回給用戶,沒有再去邏輯層 執(zhí)行視圖函數(shù)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • PyInstaller將Python文件打包為exe后如何反編譯(破解源碼)以及防止反編譯

    PyInstaller將Python文件打包為exe后如何反編譯(破解源碼)以及防止反編譯

    這篇文章主要介紹了PyInstaller將Python文件打包為exe后如何反編譯(破解源碼)以及防止反編譯,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • 使用pytorch實(shí)現(xiàn)線性回歸

    使用pytorch實(shí)現(xiàn)線性回歸

    這篇文章主要為大家詳細(xì)介紹了使用pytorch實(shí)現(xiàn)線性回歸,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-04-04
  • Pandas讀取csv的實(shí)現(xiàn)

    Pandas讀取csv的實(shí)現(xiàn)

    本文主要介紹了Pandas讀取csv的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-01-01
  • Python django使用多進(jìn)程連接mysql錯(cuò)誤的解決方法

    Python django使用多進(jìn)程連接mysql錯(cuò)誤的解決方法

    這篇文章主要介紹了Python django使用多進(jìn)程連接mysql錯(cuò)誤的解決方法,詳細(xì)的介紹了解決方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-10-10
  • python設(shè)計(jì)微型小說網(wǎng)站(基于Django+Bootstrap框架)

    python設(shè)計(jì)微型小說網(wǎng)站(基于Django+Bootstrap框架)

    這篇文章主要介紹了python設(shè)計(jì)微型小說網(wǎng)站(基于Django+Bootstrap框架),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Python利用Matplotlib繪制圖表詳解

    Python利用Matplotlib繪制圖表詳解

    Matplotlib是Python中最受歡迎的數(shù)據(jù)可視化軟件包之一,支持跨平臺(tái)運(yùn)行,它是Python常用的 2D 繪圖庫。本文將介紹如何通過Matplotlib繪制常用的圖表
    2022-01-01
  • Django ORM 常用字段與不常用字段匯總

    Django ORM 常用字段與不常用字段匯總

    這篇文章主要介紹了Django ORM 常用字段與不常用字段匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • python數(shù)據(jù)清洗中的時(shí)間格式化實(shí)現(xiàn)

    python數(shù)據(jù)清洗中的時(shí)間格式化實(shí)現(xiàn)

    本文主要介紹了python數(shù)據(jù)清洗中的時(shí)間格式化實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • Python中sort和sorted函數(shù)代碼解析

    Python中sort和sorted函數(shù)代碼解析

    這篇文章主要介紹了Python中sort和sorted函數(shù)代碼解析,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01
  • 教你用Python爬取英雄聯(lián)盟皮膚原畫

    教你用Python爬取英雄聯(lián)盟皮膚原畫

    今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識(shí),文章圍繞著用Python爬取英雄聯(lián)盟皮膚原畫展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06

最新評(píng)論

修武县| 乐都县| 淮北市| 华宁县| 阿图什市| 长岭县| 加查县| 申扎县| 泸溪县| 灵丘县| 商洛市| 甘谷县| 五原县| 岑巩县| 广昌县| 天津市| 明水县| 西畴县| 金门县| 建水县| 札达县| 麦盖提县| 定州市| 丰顺县| 德保县| 米泉市| 饶河县| 开鲁县| 鹿邑县| 开原市| 昔阳县| 安乡县| 兴义市| 施秉县| 华安县| 岳普湖县| 金塔县| 河源市| 扎兰屯市| 高清| 绵竹市|