您好!欢迎来到北极熊

北极熊

热门搜索: 任正非传    神雕侠侣    红楼梦   

Django 整合 Swagger 两分钟完成

分类:技术交流 时间:2020-10-21 17:39 浏览:212
概述
Django Admin 还有 browser API 是方便浏览操作API, 但是不太适合全局阅读,而Swagger UI 是公认的API 文档说明最好的,只需要花费两分钟就可以配置好,这里我们不使用django-rest-swagger,这个作者已经弃用多年,我们使用drf-yasg2官方
内容

Django Admin 还有 browser API 是方便浏览操作API, 但是不太适合全局阅读,而Swagger UI 是公认的API 文档说明最好的,

只需要花费两分钟就可以配置好,这里我们不使用django-rest-swagger,这个作者已经弃用多年,我们使用drf-yasg2

官方文档上推荐使用drf-yasg,但是它不能兼容最新的DRF,所以我们使用drf-yasg2

 

pip install drf-yasg2

更新项目文件里的 settings.py 来加载 drf_yasg2 

# Application definitionINSTALLED_APPS = ['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','drf_yasg2', # <---- 这里'django_filters','tweets']

更新项目里的 urls.py 文件来加载 the schema_view

# drf_yasg2 从这里开始from rest_framework import permissionsfrom drf_yasg2.views import get_schema_viewfrom drf_yasg2 import openapischema_view = get_schema_view(openapi.Info(title="Tweet API",default_version='v1',description="Welcome to the world of Tweet",terms_of_service="https://www.tweet.org",contact=openapi.Contact(email="demo@tweet.org"),license=openapi.License(name="Awesome IP"),),public=True,permission_classes=(permissions.AllowAny,),)# 这里结束urlpatterns = [re_path(r'^doc(?P<format>\.json|\.yaml)$',schema_view.without_ui(cache_timeout=0), name='schema-json'),  #<-- 这里path('doc/', 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'),  #<-- 这里path(r'polls/', include('polls.urls')),path(r'tweet/', include('tweets.urls')),path(r'admin/', admin.site.urls),path(r'api-auth/', include(('rest_framework.urls', 'rest_framework'), namespace="api-auth"))]

运行项目:

 

redoc:

 

配置完成


评论
资讯正文页右侧广告
联系我们
电话:18936411277
邮箱:1044412291@qq.com
时间:09:00 - 19:00
公众号:北格软件
底部广告