如何在 Django 中编写自定义装饰器? [英] How to write a custom decorator in django?

查看:30
本文介绍了如何在 Django 中编写自定义装饰器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题-

@is_premium_user
def sample_view:
          .......
          ......

我希望只有网站的高级用户才能访问某些视图.
我如何在我的项目中的各种应用程序中使用这个装饰器?

I want certain views accesible to only the premium users of the website.
And how can I use this decorator across various applications in my project?

推荐答案

您不必为此编写自己的装饰器 user_passes_test 已经包含在 Django 中.

You don't have to write your own decorator for this as user_passes_test is already included in Django.

还有一个片段 (group_required_decorator) 扩展了这个装饰器和这应该非常适合您的用例.

And there's a snippet (group_required_decorator) that extends this decorator and which should be pretty appropriate for your use case.

如果您真的想编写自己的装饰器,那么有很多 网络上的好文档.

If you really want to write your own decorator then there's a lot of good documentation on the net.

好吧,要(重新)使用装饰器,只需将装饰器放在路径上的一个模块中,您就可以从任何其他模块导入它.

And well, to (re-) use the decorator just put your decorator in a module on your path and you can import it from any other module.

这篇关于如何在 Django 中编写自定义装饰器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆