Chinaunix首页 | 论坛 | 博客
  • 博客访问: 648920
  • 博文数量: 107
  • 博客积分: 4135
  • 博客等级: 上校
  • 技术积分: 1182
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-06 16:01
文章分类

全部博文(107)

文章存档

2020年(2)

2012年(5)

2011年(6)

2010年(23)

2009年(17)

2008年(35)

2007年(19)

我的朋友

分类: Web开发

2020-10-22 22:47:42

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 

  1. # Application definition
  2. INSTALLED_APPS = [
  3. 'django.contrib.admin',
  4. 'django.contrib.auth',
  5. 'django.contrib.contenttypes',
  6. 'django.contrib.sessions',
  7. 'django.contrib.messages',
  8. 'django.contrib.staticfiles',
  9. 'rest_framework',
  10. 'drf_yasg2', # <---- 这里
  11. 'django_filters',
  12. 'tweets'
  13. ]

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

  1. # drf_yasg2 从这里开始
  2. from rest_framework import permissions
  3. from drf_yasg2.views import get_schema_view
  4. from drf_yasg2 import openapi
  5. schema_view = get_schema_view(
  6. openapi.Info(
  7. title="Tweet API",
  8. default_version='v1',
  9. description="Welcome to the world of Tweet",
  10. terms_of_service="",
  11. contact=openapi.Contact(email="demo@tweet.org"),
  12. license=openapi.License(name="Awesome IP"),
  13. ),
  14. public=True,
  15. permission_classes=(permissions.AllowAny,),
  16. )
  17. # 这里结束
  18. urlpatterns = [
  19. re_path(r'^doc(?P\.json|\.yaml)$',schema_view.without_ui(cache_timeout=0), name='schema-json'), #<-- 这里
  20. path('doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), #<-- 这里
  21. path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), #<-- 这里
  22. path(r'polls/', include('polls.urls')),
  23. path(r'tweet/', include('tweets.urls')),
  24. path(r'admin/', admin.site.urls),
  25. path(r'api-auth/', include(('rest_framework.urls', 'rest_framework'), namespace="api-auth"))
  26. ]

运行项目:

 

redoc:

 

配置完成

阅读(1203) | 评论(0) | 转发(0) |
0

上一篇:Angular 配合 angulartics2 跟踪分析用户行为

下一篇:没有了

给主人留下些什么吧!~~