时间:2018-02-06 关注公众号 来源:网络
本文研究的主要是Python使用装饰器进行django开发的相关内容,具体如下。
装饰器可以给一个函数,方法或类进行加工,添加额外的功能。

在这篇中使用装饰器给页面添加session而不让直接访问index,和show。在views.py中
?
1 2 3 4 5 | Stream Vera Sans Mono', 'Courier New', Courier, monospace !important; float: none !important; border-top-width: 0px !important; border-bottom-width: 0px !important; height: auto !important; color: rgb(0, 102, 153) !important; vertical-align: baseline !important; overflow: visible !important; top: auto !important; right: auto !important; font-weight: bold !important; left: auto !important; background-image: initial; background-attachment: initial; background-size: initial; background-origin: initial; background-clip: initial; background-position: initial; background-repeat: initial;" class="py keyword">def index(request): return HttpResponse('index') def show(request): return HttpResponse('show') |
这样可以直接访问index和show,如果只允许登陆过的用户访问index和show,那么就需修改代码
?
1 2 3 4 5 6 7 8 9 10 | 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') |
这样可以实现限制登陆过的用户访问功能,但是代码中也出现了许多的相同部分,于是可以把这些相同的部分写入一个函数中,用这样一个函数装饰index和show。这样的函数就是装饰器。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 | def decorator(main_func): def wrapper(request): #index,show中是一个参数,所以在wrapper中也是一个参数 if request.session.get('username'): return main_func(request) else: return HttpResponse('login') return wrapper @decoratordef index(request): return HttpResponse('index')def show(request): return HttpResponse('show') |
这样在视图函数中只要是一个参数就可以通过decorator函数装饰,如果有两个参数就需要修改装饰器
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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 @decoratordef index(request): return HttpResponse('index') @decorator1def show(request,page): return HttpResponse('show') |
这个如果有一个参数就通过decorator来修饰,如果有两个参数就通过decorator1来修饰。于是可以通过动态参数的方式来结合decorator和decorator1,可以同时修饰index和show。
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 @decorator3def index(request,*args,**kwargs): return HttpResponse('index')@decorator3def show(request,*args,**kwargs): return HttpResponse('show') |