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

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

我正在尝试在 Django REST framework 中为我的 REST API 定义 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

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

最佳答案

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

关于python - 为 get 和 post 请求定义不同的模式 - AutoSchema Django Rest Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59468988/

相关文章:

python - 如何使用 Pandas ExcelWriter 将空工作表添加到现有工作簿中

python - 使用 Selenium 和 BeautifulSoup 提取 iFrame 内容

Django 1.9.2 测试客户端问题

serialization - Django-rest-framework,序列化程序中的嵌套对象

javascript - Django 与谷歌图表

python - sphinx_rtd_theme 从 1.4.0 版本开始不再是硬依赖

Django 和 ModelForm 上的字段集

python - 排除 django 查询集中的重复对象

python - 删除N个随机对象Django orm

django-rest-framework - 在Django rest框架中将Validationerror转换为serializers.Validationerror