如何在Django中将装饰器应用于(模块的)所有视图 [英] How to apply a decorator to all views (of a module) in django

查看:52
本文介绍了如何在Django中将装饰器应用于(模块的)所有视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当特定模块中的所有视图仅在获得用户授权时才可用,或者应该都进行相同的检查时,会发生很多情况.

It happens a lot, when all the views in a specific module are supposed to be available only when the user is authorized, or they should all do the same checks.

如何避免在整个文件中重复注释?

How could I avoid repeating the annotations all over the file?

推荐答案

使用基于类的视图时,可以为所有这些视图创建基类/混合,以实现所需的功能(也可以使用

When using class-based views you can create a base class/mixin for all these views which implements the desired functionality (also using decorators) and then have all the views inherit from this base view.

from django.views.generic import TemplateView

class BaseView(TemplateView):

    def get(self, request, *args, **kwargs):
        # do some checking here
        if not request.user.is_authenticated():
            # do something if anonymous user
        return super(BaseView, self).get(request, *args, **kwargs)


class MyView(BaseView):
    pass

这篇关于如何在Django中将装饰器应用于(模块的)所有视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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