您的位置:首页 > 编程语言 > Go语言

自定义Django的Decorators

2014-07-18 18:36 218 查看
在Django中我们在方法前面会看到这样一类的方法:

@login_required
def sayhello(request):
print "helloworld"
其中的 login_required 我们称为 装饰器。

如果你要自定义装饰器,步骤如下:

1.建一个文件:decorators.py

2.文件中代码如下:

# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template import RequestContext
from .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_func
3.在views.py中:

# -*- coding: utf-8 -*-
from .decorators import check_user

@check_user
def checkuserinfo(request):
<span style="white-space:pre">	</span>print "hello"


这样设置后,当用户名为bendan的人调用方法checkuserinfo时,页面就会重定向到登陆页面;而其他用户则不受影响,继续调用checkuserinfo方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django decorators