4

我正在尝试在 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

问题是我想要获取和发布请求的不同架构。如何使用 AutoSchema 实现这一目标?

4

2 回答 2

4

您可以创建自定义 Schema并覆盖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()
    ...
于 2020-01-03T00:27:08.197 回答
-1

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

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
于 2019-12-28T17:05:28.493 回答