使用drf_yasg生成drf接口文檔 會有參數類型,比drf自己的更完善


1.安裝庫

**pip install drf-yasg**

2.配置setting

INSTALLED_APPS = [
...
'drf_yasg',
...
]

3.配置全局路由文件urls.py

點擊查看代碼
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="API接口文檔平台",  # 必傳
        default_version='v1',  # 必傳
        description="這是一個接口文檔",
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    # permission_classes=(permissions.AllowAny,),   # 權限類
)

urlpatterns = [
    ...
    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
]

4.查看

http://127.0.0.1:8000/redoc/
image

http://127.0.0.1:8000/swagger/
image

5.重點

對於沒有使用drf序列化的一些高層接口,我們可以使用底層的APIView來創建視圖集,並使用drf_yasg生成接口文檔。

點擊查看代碼
from django.shortcuts import render, HttpResponse
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from drf_yasg.openapi import Schema, Response


class NoneModelViewSet(APIView):

    @swagger_auto_schema(
        tags=['沒模型測試'],
        operation_description='沒模型get',
        operation_summary='沒模型摘要get', )
    def get(self, request, *args, **kwargs):
        print(11111, request.GET)
        return HttpResponse('ok')

    @swagger_auto_schema(
        tags=['沒模型測試'],
        operation_description='沒模型post',
        operation_summary='沒模型摘要post',
        request_body=Schema(type=openapi.TYPE_OBJECT,
                            required=['account_id'],
                            properties={
                                'account_id': Schema(
                                    description='用戶id example: 12354',
                                    type=openapi.TYPE_INTEGER),
                                'telephone': Schema(
                                    description='手機號碼 example: 19811111111',
                                    type=openapi.TYPE_STRING),
                                'code': Schema(
                                    description='兌換碼 example: 15462fd',
                                    type=openapi.TYPE_STRING),
                                'disguise_change': Schema(
                                    description='是否是偽變化 example: 0表示不是,1 表示是',
                                    type=openapi.TYPE_INTEGER, enum=[0, 1]),
                            }),
        responses={
            400: Response(description='操作失敗', examples={'json': {'code': -1, 'msg': '失敗原因'}}),
            200: Response(description='操作成功', examples={'json': {'code': 0, 'msg': '成功'}})
        }
    )
    def post(self, request):
        print(request.body)
        return HttpResponse('ok')![image](https://img2022.cnblogs.com/blog/1224392/202203/1224392-20220310142751732-445834818.png)


urls.py

點擊查看代碼
urlpatterns = [
    path('index', index),
    path('none_model', NoneModelViewSet.as_view())
]

查看接口文檔

http://127.0.0.1:8000/redoc/
image

http://127.0.0.1:8000/swagger
image

6.優化模型類視圖集

如果直接生成模型類視圖集,就會像4顯示的一樣,標簽是路由名,不像5中,顯示的是自定義的漢字。所以用重寫父類方法,然后用swagger_auto_schema裝飾器對標簽進行命名。代碼如下:

點擊查看代碼
class GenerateRecordViewSet(viewsets.ModelViewSet):
    queryset = GenerateRecord.objects.all()
    serializer_class = GenerateRecordSerializer
    pagination_class = LargeResultsSetPagination
    http_method_names = ['get', 'post', 'put']
    tag = ['兌換碼']

    @swagger_auto_schema(tags=tag, operation_summary='獲取所有兌換碼', operation_description='獲取所有兌換碼')
    def list(self, request, *args, **kwargs):
        return super(GenerateRecordViewSet, self).list(request, *args, **kwargs)

    @swagger_auto_schema(tags=tag, operation_summary='獲取單個兌換碼', operation_description='通過id獲取單個兌換碼信息')
    def retrieve(self, request, *args, **kwargs):
        return super(GenerateRecordViewSet, self).retrieve(request, *args, **kwargs)

    @swagger_auto_schema(tags=tag, operation_summary='生成兌換碼', operation_description='生成兌換碼')
    def create(self, request, *args, **kwargs):
        return super(GenerateRecordViewSet, self).create(request, *args, **kwargs)

    @swagger_auto_schema(tags=tag, operation_summary='兌換碼上下架', operation_description='修改有效標志')
    def update(self, request, *args, **kwargs):
        return super(GenerateRecordViewSet, self).update(request, *args, **kwargs)

查看

http://127.0.0.1:8000/swagger
image
http://127.0.0.1:8000/redoc
image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM