【问题标题】:Defining different schema for both get and post request - AutoSchema Django Rest Framework为 get 和 post 请求定义不同的模式 - AutoSchema Django Rest Framework
【发布时间】:2020-04-15 13:10:47
【问题描述】:

我正在尝试在 Django REST 框架中为我的 REST API 定义 AutoSchema(将在 django REST 框架 swagger 中显示)。有这个类扩展了 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 实现这一点?

【问题讨论】:

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


【解决方案1】:

您可以创建自定义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()
    ...

【讨论】:

  • 应该是manual_fields = super().get_manual_fields(path, method)
【解决方案2】:

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

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-05-04
    • 2018-12-22
    • 1970-01-01
    • 2016-12-29
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 2019-01-07
    相关资源
    最近更新 更多