2024-03-29 05:22:38 发布
网友
问题是-
@is_premium_user def sample_view: ....... ......
我希望只有网站的高级用户才能访问某些视图。 如何在项目中的各种应用程序中使用此装饰器?
玩了上面的各种链接,却无法让他们工作,然后遇到了这个非常简单的我适应了。http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/
from functools import wraps from django.http import HttpResponseRedirect def authors_only(function): @wraps(function) def wrap(request, *args, **kwargs): profile = request.user.get_profile() if profile.usertype == 'Author': return function(request, *args, **kwargs) else: return HttpResponseRedirect('/') return wrap
使用@wraps比像使用wrap.__doc__ = fn.__doc__那样手动重写要好。除此之外,它还确保包装函数与包装函数的名称相同。
@wraps
wrap.__doc__ = fn.__doc__
见https://docs.python.org/2/library/functools.html
您不必为此编写自己的decorator,因为^{}已经包含在Django中。
还有一个片段(^{})扩展了这个decorator,它应该非常适合您的用例。
如果你真的想写你自己的装饰,那么网上有很多good documentation。
而且,要(重新)使用decorator,只需将decorator放在路径上的一个模块中,就可以从任何其他模块导入它。
多亏了阿里,这个答案帮了我很大的忙,但对我不起作用。
当我找到这个片段时,我让它正常工作:http://djangosnippets.org/snippets/983/
这个解决方案对我有效:
帮助函数
此函数的好处是可以在其他地方重用,作为user.is_authenticated的替换项。例如,它可以作为模板标记公开。
user.is_authenticated
def my_custom_authenticated(user): if user: if user.is_authenticated(): return user.groups.filter(name=settings.MY_CUSTOM_GROUP_NAME).exists() return False
装饰工
我只是把这个放在我的views.py上面,因为它太短了。
views.py
def membership_required(fn=None): decorator = user_passes_test(my_custom_authenticated) if fn: return decorator(fn) return decorator
使用它
@membership_required def some_view(request): ...
玩了上面的各种链接,却无法让他们工作,然后遇到了这个非常简单的我适应了。http://code.activestate.com/recipes/498217-custom-django-login_required-decorator/
使用
@wraps
比像使用wrap.__doc__ = fn.__doc__
那样手动重写要好。除此之外,它还确保包装函数与包装函数的名称相同。见https://docs.python.org/2/library/functools.html
您不必为此编写自己的decorator,因为^{} 已经包含在Django中。
还有一个片段(^{} )扩展了这个decorator,它应该非常适合您的用例。
如果你真的想写你自己的装饰,那么网上有很多good documentation。
而且,要(重新)使用decorator,只需将decorator放在路径上的一个模块中,就可以从任何其他模块导入它。
多亏了阿里,这个答案帮了我很大的忙,但对我不起作用。
当我找到这个片段时,我让它正常工作:http://djangosnippets.org/snippets/983/
这个解决方案对我有效:
帮助函数
此函数的好处是可以在其他地方重用,作为
user.is_authenticated
的替换项。例如,它可以作为模板标记公开。装饰工
我只是把这个放在我的
views.py
上面,因为它太短了。使用它
相关问题 更多 >
编程相关推荐