自定义Django的Decorators
来源:互联网 发布:php ajax传值 编辑:程序博客网 时间:2024/06/08 06:05
在Django中我们在方法前面会看到这样一类的方法:
@login_requireddef sayhello(request):print "helloworld"其中的 login_required 我们称为 装饰器。
如果你要自定义装饰器,步骤如下:
1.建一个文件:decorators.py
2.文件中代码如下:
# -*- coding: utf-8 -*-from django.core.urlresolvers import reverse from django.http import HttpResponseRedirectfrom django.template import RequestContextfrom .models import User# 验证用户def check_user(view_func): # 此方法为包裹view_func的方法# 我们可以在这里定义自己需要的功能 def _wrapped_view_func(request, *args, **kwargs): try: user = User.objects.get(user=request.user.id) except CampusUser.DoesNotExist: user = User.objects.none() # 如果用户名为bendan,则重定向到登陆页面 if user and user.name == "bendan": return HttpResponseRedirect('/login') # 返回包裹的方法 return view_func(request, *args, **kwargs) return _wrapped_view_func3.在views.py中:
# -*- coding: utf-8 -*-from .decorators import check_user@check_userdef checkuserinfo(request):<span style="white-space:pre"></span>print "hello"
这样设置后,当用户名为bendan的人调用方法checkuserinfo时,页面就会重定向到登陆页面;而其他用户则不受影响,继续调用checkuserinfo方法。
0 0
- 自定义Django的Decorators
- python 的函数Decorators
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- struts的decorators.xml
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- decorators.xml的用法
- Sitemesh 自定义decorators.xml 文件路径
- 使用sitemesh的decorators功能
- Linux系统优化
- IOS侦测蓝牙是否开启
- 安卓学习笔记(三)分类排版说明——安卓第三天
- 12 个免费在线的 Web 网站性能测试工具
- dns
- 自定义Django的Decorators
- android监听home键
- 好的产品经理是怎样炼成的?
- LeetCode OJ - Search Insert Position
- 双目相机的畸变校正以及平行校正(极线校正)的入门问题总结
- OBJECTIVE-C中nsstring的writetofile atomically参数解释
- c++ const,引用,STL容器
- Swift语言从天而降,能否掀起新一轮的科技革命?
- C语言学习随笔