Django Rest Framework: How to enable swagger docs for function based views

眉间皱痕 提交于 2019-12-04 02:46:57

问题


I went through Django REST Swagger 2.1.2 documentation. When I tried with class based views, it was working fine.

But i did not find any reference on how to enable swagger for function based views as shown below:

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

Most of my views.py is filled with function based views, just like above.

Any help on how to enable the same will greatly appreciated. Thanks!

I am using Django: 1.8; Django REST Swagger: 2.1.2; DRF: 3.6.2


回答1:


You should be able to use @renderer_classes decorator:

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

Also, it should be worth mentioning, that if you don't want to use this decorator on every view you can specify DEFAULT_RENDERER_CLASSES in settings

EDIT: It seems it's in the docs after all. Check the very bottom of this page: https://django-rest-swagger.readthedocs.io/en/latest/schema/




回答2:


i am not fammiliar with swagger,but you may try to use the decorator in this way:

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

or

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

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

sorry, maybe i have misunderstood your question. according to the document, if you want to enable swagger in class based view. there is example:

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 will use these two renderer_classes to render Json and UI.



来源:https://stackoverflow.com/questions/43627748/django-rest-framework-how-to-enable-swagger-docs-for-function-based-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!