django项目中使用swagger来实现接口文档自动生成

一、Swagger

一般我们在对接前后端的时候,都需要提供相应的接口文档。对于后端来说,编写接口文档即费时费力,还会经常因为没有及时更新,导致前端对接时出现实际接口与文档不一致。而且手写接口文档还容易出错,而swagger很好的解决了这个痛点。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。可用于:1.接口的文档在线自动生成、2.功能测试。

 

二、在DjangorestFramework中自动生成接口文档drf_yasg

REST framework可以自动帮助我们生成接口文档。

接口文档以网页的方式呈现。

自动接口文档能生成的是继承自APIView及其子类的视图。

# 安装
pip install   drf_yasg

# 添加
INSTALLED_APPS = [
    'drf_yasg',
    'rest_framework'
,   
]
# urls.py

from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
    openapi.Info(
        title="接口文档平台",  # 必传
        default_version='v1',  # 必传
        description="文档描述",
        terms_of_service='',
        contact=openapi.Contact(email="###@qq.com"),
        license=openapi.License(name="BSD LICENSE")
    ),
    public=True,
    # permission_classes=(permissions.)  # 权限类
# permission_classes=(permissions.AllowAny,) # 可以允许任何人查看该接口
# permission_classes=(permissions.IsAuthenticated) # 只允许通过认证的查看该接口
) urlpatterns += [ # re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0)), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ]
# settings.py
# Swagger配置 https://github.com/axnsan12/drf-yasg/issues/58
SWAGGER_SETTINGS = {
    'USE_SESSION_AUTH': False,
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
}

 

 

 

 

drf_yasg官网:https://drf-yasg.readthedocs.io/

drf_yasg:https://github.com/axnsan12/drf-yasg

posted on 2022-12-29 13:26  一先生94  阅读(839)  评论(0编辑  收藏  举报

导航