Python使用裝飾器進(jìn)行django開發(fā)實例代碼
本文研究的主要是Python使用裝飾器進(jìn)行django開發(fā)的相關(guān)內(nèi)容,具體如下。
裝飾器可以給一個函數(shù),方法或類進(jìn)行加工,添加額外的功能。
在這篇中使用裝飾器給頁面添加session而不讓直接訪問index,和show。在views.py中
def index(request):
return HttpResponse('index')
def show(request):
return HttpResponse('show')
這樣可以直接訪問index和show,如果只允許登陸過的用戶訪問index和show,那么就需修改代碼
def index(request):
if request.session.get('username'):
return HttpResponse('index')
else:
return HttpResponse('login')<br data-filtered="filtered">
def show(request):
if request.session.get('username'):
return HttpResponse('show')
else:
return HttpResponse('login')
這樣可以實現(xiàn)限制登陸過的用戶訪問功能,但是代碼中也出現(xiàn)了許多的相同部分,于是可以把這些相同的部分寫入一個函數(shù)中,用這樣一個函數(shù)裝飾index和show。這樣的函數(shù)就是裝飾器。
def decorator(main_func):
def wrapper(request): #index,show中是一個參數(shù),所以在wrapper中也是一個參數(shù)
if request.session.get('username'):
return main_func(request)
else:
return HttpResponse('login')
return wrapper
@decorator
def index(request):
return HttpResponse('index')
def show(request):
return HttpResponse('show')
這樣在視圖函數(shù)中只要是一個參數(shù)就可以通過decorator函數(shù)裝飾,如果有兩個參數(shù)就需要修改裝飾器
def decorator(main_func):
def wrapper(request):
if request.session.get('username'):
return main_func(request)
else:
return HttpResponse('login')
return wrapper
def decorator1(main_func):
def wrapper(request,page):
if request.session.get('username'):
return main_func(request,page)
else:
return HttpResponse('login')
return wrapper
@decorator
def index(request):
return HttpResponse('index')
@decorator1
def show(request,page):
return HttpResponse('show')
這個如果有一個參數(shù)就通過decorator來修飾,如果有兩個參數(shù)就通過decorator1來修飾。于是可以通過動態(tài)參數(shù)的方式來結(jié)合decorator和decorator1,可以同時修飾index和show。
def decorator3(main_func):
def wrapper(request,*args,**kwargs):
if not request.session.get('username'):
return main_func(request,*args,**kwargs)
else:
return HttpResponse('login')
return wrapper
@decorator3
def index(request,*args,**kwargs):
return HttpResponse('index')
@decorator3
def show(request,*args,**kwargs):
return HttpResponse('show')
總結(jié)
以上就是本文關(guān)于Python使用裝飾器進(jìn)行django開發(fā)實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
Python之虛擬環(huán)境virtualenv,pipreqs生成項目依賴第三方包的方法
今天小編就為大家分享一篇Python之虛擬環(huán)境virtualenv,pipreqs生成項目依賴第三方包的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
python數(shù)據(jù)可視化JupyterLab實用擴(kuò)展程序Mito
這篇文章主要為大家介紹了python數(shù)據(jù)可視化JupyterLab實用擴(kuò)展程序Mito的功能應(yīng)用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
python中join與os.path.join()函數(shù)實例詳解
os.path.join()函數(shù)用于路徑拼接文件路徑,下面這篇文章主要給大家介紹了關(guān)于python中join與os.path.join()函數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03
Pycharm安裝并配置jupyter notebook的實現(xiàn)
這篇文章主要介紹了Pycharm安裝并配置jupyter notebook的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

