2

我有以下视图集:

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
    permission_classes = [permissions.AllowAny]

    # note that no methods are overridden

我想drf_yasg生成自定义模式,以便将所有操作方法标记为Authors.

文档说我的选择是通过声明和使用来装饰每个方法,@swagger_auto_schema如下所示:

class AuthorViewSet(viewsets.ModelViewSet):
    # ...
    @swagger_auto_schema(tags=["Authors"])
    def list(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)

或者像这样使用Django @method_decorator

@method_decorator(name="list", decorator=swagger_auto_schema(tags=["Authors"]))
class AuthorViewSet(viewsets.ModelViewSet):
    # ...

这两种选择都需要繁琐的重复,我想避免这种情况。

我也尝试实现自己的装饰器:

def decorate_viewset_methods(names, decorator):
    if names == "__all__":
        names = [
            "create",
            "retrieve",
            "update",
            "partial_update",
            "destroy",
            "list",
        ]

    def decorate(cls):
        for name in names:
            method = getattr(cls, name)
            setattr(cls, name, decorator(method))
        return cls

    return decorate

但这并不完全奏效。

所以我的问题是如何一次装饰所有的动作方法?

4

1 回答 1

13

我最终使用了这样的东西:

首先创建一个自定义自动模式

class CustomAutoSchema(SwaggerAutoSchema):

    def get_tags(self, operation_keys=None):
        tags = self.overrides.get('tags', None) or getattr(self.view, 'my_tags', [])
        if not tags:
            tags = [operation_keys[0]]

        return tags

在您的设置文件中添加:

SWAGGER_SETTINGS = {"DEFAULT_AUTO_SCHEMA_CLASS":"path.to.CustomAutoSchema"}

在你看来:

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer
    permission_classes = [permissions.AllowAny]
    my_tags = ["Authors"]
于 2020-10-20T07:54:22.897 回答