Django Rest Framework:如何为基于函数的视图启用swagger文档

时间:2017-04-26 07:33:12

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

我经历了Django REST Swagger 2.1.2 documentation。当我尝试使用基于类的视图时,它工作正常。

但是我没有找到关于如何为基于函数的视图启用swagger的任何参考,如下所示:

@api_view(['GET', 'POST'])
def app_info(request): 
    ...
    return response

我的大多数views.py都填充了基于功能的视图,就像上面一样。

如何启用相同的任何帮助将非常感谢。谢谢!

我正在使用 Django:1.8; Django REST Swagger:2.1.2; DRF:3.6.2

3 个答案:

答案 0 :(得分:15)

您应该可以使用@renderer_classes装饰器:

from rest_framework_swagger import renderers
from rest_framework.decorators import api_view, renderer_classes


@api_view(['GET', 'POST'])
@renderer_classes([renderers.OpenAPIRenderer, renderers.SwaggerUIRenderer])
def app_info(request): 
    ...
    return response

此外,值得一提的是,如果您不想在每个视图上使用此装饰器,您可以指定DEFAULT_RENDERER_CLASSES in settings

编辑:毕竟它似乎在文档中。请查看此页面的最底部:https://django-rest-swagger.readthedocs.io/en/latest/schema/

答案 1 :(得分:3)

我并不熟悉招摇,但您可以尝试以这种方式使用装饰器:

class TestView(View):
    @api_view(['GET', 'POST'])
    def get(self, request):
        ....

from django.utils.decorators import method_decorator
class TestView(View):
    @method_decorator(api_view(['GET', 'POST'])
    def get(self, request):
        ....

----------------------------------------------- -----------------------------

抱歉,也许我误解了你的问题。根据文档,如果要在基于类的视图中启用swagger。有例子:

from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.schemas import SchemaGenerator
from rest_framework.views import APIView
from rest_framework_swagger import renderers


class SwaggerSchemaView(APIView):
    permission_classes = [AllowAny]
    renderer_classes = [
        renderers.OpenAPIRenderer,
        renderers.SwaggerUIRenderer
    ]

    def get(self, request):
        generator = SchemaGenerator()
        schema = generator.get_schema(request=request)
        return Response(schema)

restframework将使用这两个renderer_classes来渲染Json和UI。

答案 2 :(得分:1)

在您的视图中添加以下内容。py

进口

from rest_framework.schemas import AutoSchema
from rest_framework.compat import coreapi
#creating custom class 
class CustomSampleSchema(AutoSchema):
    def __init__(self):
        super(CustomSampleSchema, self).__init__()

    def get_manual_fields(self, path, method):
        extra_fields = [
            coreapi.Field('field1', required=True, location='form', description='', type='', example=''),
            coreapi.Field('field2', required=False, location='form', description='', type='', example=''),
            coreapi.Field('field3', required=False, location='form', description='', type='', example='')

        ]
        manual_fields = super().get_manual_fields(path, method)
        return manual_fields + extra_fields

这是您要为其编写swagger文档的功能。

@api_view(['post'])
@schema(CustomSampleSchema())
@csrf_exempt
def func_name(request, param):
"""
Your function definition below
"""

样本json输入

{"name": "['name1', ]",
"places": "['place1', 'place2']",
"key":"12345"}