python - 如何处理类层次结构中的Python装饰器?

标签 python django oop decorator python-decorators

我正在使用 DRF 开发一个 Django 项目。我也用过drf-yasg用于文档目的。

长话短说:我正在使用基于类的 View ,并且我有一些非常相似的 API,我决定创建一个父类(super class)并在其中实现 API 的公共(public)部分!为了更清楚:

class MySuperApiView(APIView):
    permission_classes = [<some permission classes>]

    def uncommon(self):
        pass  # to be override in subclasses

    @swagger_auto_schema(request_body=request_body, responses=api_responses)
    def post(self, *args, **kwargs):
        # do some common stuff here
        self.uncommon()
        # do some other common stuff here

我只是重写子类中的uncommon方法:

class SomeCustomApi(MySuperApiView):
    def uncommon(self):
        # do specific things here

它工作正常,但我有一个小问题:每个 Api 都有自己的 api_responses ,它是在父类(super class)的 swagger_auto_schema 装饰器中初始化的!而且无法更改!

针对这种情况,您有什么建议?我真的很想做 OOP 并遵守 DRY 原则。

最佳答案

我终于找到了在 Django 中做这样的事情的最佳方法! (所以是的,我不知道如何在其他框架或语言中处理这样的问题!) 我使用名为 method_decorator 的类装饰器将 swagger_auto_schema 装饰器移动到子类。所以首先我必须导入这个方法:

from django.utils.decorators import method_decorator

然后我像这样更改了父类(super class)和子类:

class MySuperApiView(APIView):
    permission_classes = [<some permission classes>]

    def uncommon(self):
        pass  # to be override in subclasses

    # <I removed decorator from here!>
    def post(self, *args, **kwargs):
        # do some common stuff here
        self.uncommon()
        # do some other common stuff here
api_responses =  # responses which belong to "SomeCustomApi"

@method_decorator(name='post',
                  decorator=swagger_auto_schema(request_body=request_body,
                                                responses=api_responses))
class SomeCustomApi(MySuperApiView):
    def uncommon(self):
        # do specific things here

它工作得很好:)但是我更喜欢一个解决方案,在这个解决方案中我不必重复装饰器,而只需初始化 responses 参数。如果您在其他语言中遇到此类问题,并且您有其他语言的答案,请发布您的答案。

关于python - 如何处理类层次结构中的Python装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180272/

相关文章:

python - 关闭的文件描述符是怎么回事?

python - ImportError : No module named tensorflow, 但tensorflow确实存在

python - 将矩阵的行分配给新矩阵

python - Python中的语言环境日期格式

python - 在 mod_wsgi 上部署 django 应用程序时出现问题

python - 让 flup fcgi 脚本正常工作很困难

django - 使用Django分页时如何显示正确的对象编号

javascript - javascript 中访问函数和嵌套函数的区别

C++类设计问题

用于设置词汇表的 PHP OO 类