40.Django_類視圖_生成swagger接口文檔

網上很多資料在介紹Django接入Swagger方法時,都是基於django-rest-swagger庫進行講解的,都殊不知,從2019年6月份開始,官方已經廢棄了該庫,在django 3.0中已經不支持該庫了,取而代之的是全新的第三方drf-yasg庫。
1.安裝庫

pip3 install drf-yasg

2.註冊應用
settings.py文件中進行註冊第三方應用

INSTALLED_APPS = [
   
    # 註冊第三方子應用
    'polls.apps.PollsConfig', # 大部分情況簡寫成'polls'
    'rest_framework',
     'django_filters',
     #swagger接口文檔
     'drf-yasg',

     #自己創建的應用
    'projects.apps.ProjectsConfig',
    'interfaces.apps.InterfacesConfig',
]

3.添加路徑
urls.py文件中添加路徑

from django.contrib import admin
from django.urls import path, include, re_path

#2. coreapi文檔需要進行的導入信息
from rest_framework.documentation import include_docs_urls


#swagger接口文檔

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.0',
        description="接口平臺接口文檔",
        terms_of_service="#",
        contact=openapi.Contact(email="測試"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
)

urlpatterns = [
    # path('/', include('projects.urls')),
    path('admin/', admin.site.urls),  # 進入localhost:8000/admin會進入Django的admin管理頁面
    path('polls/', include('polls.urls')),
    path('', include('projects.urls')),
    path('interfaces/', include('interfaces.urls')),


   #3. coreapi文檔路徑
    path('docs/',include_docs_urls(title="接口測試平臺API文檔",
                                   description="這個是接口平臺的文檔"
                                   )),

    # 配置drf-yasg路由
    re_path('^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
    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.運行:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章