Python使用装饰器进行django开发实例代码
2018-02-06 10:55
1061 查看
本文研究的主要是Python使用装饰器进行django开发的相关内容,具体如下。
装饰器可以给一个函数,方法或类进行加工,添加额外的功能。
在这篇中使用装饰器给页面添加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')
这样可以实现限制登陆过的用户访问功能,但是代码中也出现了许多的相同部分,于是可以把这些相同的部分写入一个函数中,用这样一个函数装饰index和show。这样的函数就是装饰器。
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函数装饰,如果有两个参数就需要修改装饰器
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')
这个如果有一个参数就通过decorator来修饰,如果有两个参数就通过decorator1来修饰。于是可以通过动态参数的方式来结合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')
总结
以上就是本文关于Python使用装饰器进行django开发实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
您可能感兴趣的文章:
相关文章推荐
- Python中使用django框架进行web开发,模板中无法导入css、js和图片的问题解决
- 使用pycharm手动搭建python语言django开发环境 - 使用git管理代码(二)
- 使用C语言进行面向对象的开发--GObject入门[实例代码]
- 使用Flex 4、Django、Python和PyAMF进行开发
- 使用Python进行QQ批量登录的实例代码
- Django中使用jquery的ajax进行数据交互的实例代码
- 使用Flex 4、Django、Python和PyAMF进行开发
- python使用pil进行图像处理(等比例压缩、裁剪)实例代码
- 使用python进行桌面程序开发(一)
- 一步一步教你使用AgileEAS.NET基础类库进行应用开发-WinForm应用篇-实例一个模块(商品字典)
- 使用InfoPath和SharePoint Designer进行无代码工作流开发
- 使用Aptana+Pydev构建Python开发环境(Django)
- 使用rope进行Python代码补全
- Python Web 框架,第 1 部分: 使用 Django 和 Python 开发 Web 站点
- 使用Python进行AES加密和解密的示例代码
- 使用python进行桌面程序开发(二)
- 使用ropemacs对python代码进行补全
- 三层模式开发使用GridPanel(.net)控件代码实例详解(展示层代码)
- 使用 Django 和 Python 开发 Web 站点
- Python Web 框架,第 1 部分: 使用 Django 和 Python 开发 Web 站点