为get和post请求AutoSchema Django Rest Fram定义不同的模式

2024-05-29 05:21:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django rest框架中为我的restapi定义AutoSchema(将在django rest framework 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

问题是get和post请求都需要不同的模式。如何使用AutoSchema实现这一点?在


Tags: ofthedjangoresttruefieldgetrequired
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

您可以创建自定义架构并重写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()
    ...

相关问题 更多 >

    热门问题