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   一先生94  阅读(874)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示