Django 整合 Swagger 两分钟完成

 

 

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 definition

INSTALLED_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 permissions
from drf_yasg2.views import get_schema_view
from drf_yasg2 import openapi
schema_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:

 

配置完成

  • 9
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值