为获取和发布请求定义不同的模式-AutoSchema Django Rest Framework

时间:2019-12-24 12:39:41

标签: python django django-rest-framework django-rest-swagger

我正在尝试为Django REST框架中的REST API定义AutoSchema(将在django rest框架中显示)。此类扩展了APIView。

该类同时具有“ get”和“ post”方法。喜欢:

class Profile(APIView):
permission_classes = (permissions.AllowAny,)
schema = AutoSchema(
    manual_fields=[
        coreapi.Field("username",
                      required=True,
                      location='query',
                      description='Username of the user'),

    ]
)
def get(self, request):
    return
schema = AutoSchema(
    manual_fields=[
        coreapi.Field("username",
                      required=True,
                      location='form',
                      description='Username of the user '),
        coreapi.Field("bio",
                      required=True,
                      location='form',
                      description='Bio of the user'),

    ]
)
def post(self, request):
    return

问题是我希望get和post请求都使用不同的架构。如何使用AutoSchema实现此目的?

2 个答案:

答案 0 :(得分:2)

您可以创建自定义架构,并覆盖get_manual_fields方法以基于以下方法提供自定义manual_fields列表:

class CustomProfileSchema(AutoSchema):
    manual_fields = []  # common fields

    def get_manual_fields(self, path, method):
        custom_fields = []
        if method.lower() == "get":
            custom_fields = [
                coreapi.Field(
                    "username",
                    required=True,
                    location='form',
                    description='Username of the user '
                ),
                coreapi.Field(
                    "bio",
                    required=True,
                    location='form',
                    description='Bio of the user'
                ),
            ]
        if method.lower() == "post":
            custom_fields = [
                coreapi.Field(
                    "username",
                    required=True,
                    location='query',
                    description='Username of the user'
                ),
            ]
        return self._manual_fields + custom_fields


class Profile(APIView):
    schema = CustomProfileSchema()
    ...

答案 1 :(得分:0)

如果我正确理解了您的问题,则可以在每种方法中定义模式,如下所示:

class Profile(APIView):
    def get(self, request):
         # your logic
         self.schema = AutoSchema(...) # your 'get' schema
         return

    def post(self, request):
        self.schema = AutoSchema(...) # your 'post' schema
        return