django-rest-swagger UI 没有 POST 请求主体的形式(基于函数的视图)

django-rest-swagger UI doesn't have form for POST request body (function based view)

我有这个 基于函数的视图 并装饰了 django-rest-swagger。但是,我无法在 UI 中找到允许我 post 有效负载 (request.body) 的位置。

我看到了一些关于使用基于 class 的视图来实现它的解决方案,但我想知道是否有一种方法可以使用基于函数的视图来实现它。

提前致谢!

@renderer_classes([JSONRender])
@api_view(['POST'])
def some_method(request):
    body = json.loads(request.body)
    return JsonResponse({'status': 'ok'})

我要回答我的问题,因为 django-rest-swagger 在 2019 年 6 月被 弃用 我刚刚发现了 2 个可行的解决方案。

第一个将全局更改 UI

ping.views(或您希望的任何其他位置)添加以下内容 class。

from rest_framework.schema import AutoSchema

class CustomSchema(AutoSchema):
    def __init__(self):
        super(CustomSchema, self).__init__()
    def get_manual_fields(self, path, method):
        extra_fields = [
            coreapi.Field('command', required=True, location='form', schema=String(), description='', type='', example='',
            coreapi.Field('params', required=False, location='form', schema=String(), description='', type='', example='',
        ]
        manual_fields = super().get_manual_fields(path, method)
        return manual_fields + extra_fields

在 Django 项目的 settings.py 中添加以下设置。

REST_FRAMEWORK = {
    # Corresponding path to where you added the class
    'DEFAULT_SCHEMA_CLASS': 'ping.views.CustomSchema', 
}

第二种解决方案可以在每个视图的基础上应用。您可以在此处查看 official guide

使用来自 rest_framework.decorators.schema 的 @schema 覆盖 DEFAULT_SCHEMA_CLASS.

@api_view(['POST'])
@schema(CustomSchema())
def your_view(request):
    print(request.body)
    return JsonResponse({'task_status': 200'})

基本上,想法是覆盖DEFAULT_SCHEMA_CLASSschema 这个词是他们用来指代 rest_framework.

中每个视图的 swagger UI 的术语

当您使用 @api_view() 修饰基于函数的视图时,它会为您的函数分配一个属性 schema,其值 APIView.schema 来自 rest_framework.views.APIView.

rest_framework.views.APIView 将进一步调用 DefaultSchema()settings.py.

中的 REST_FRAMEWORK 配置加载 DEFAULT_SCHEMA_CLASS

如果不另行说明,DEFAULT_SCHEMA_CLASS就是rest_framework.schemas.openapi.AutoSchema这个official announcement。您可能想将其更改为 rest_framework.schemas.coreapi.AutoSchema,因为它与 django_rest_swagger.

兼容

希望本教程对使用 django-rest-swagger (2.2.0) 基于函数的视图 的 Django 项目的人有所帮助。

如果有什么我可以帮助解决这个问题,请发表评论。