智慧水务项目(四)django(drf)+angular 18 添加drf_yasg api接口文档

一、说明

文档api接口是必须的

本来准备用coreapi,据说drf_yasg更流弊

二、步骤

1、requirements.txt添加drf-yasg

2、settings.py中添加部分代码

drf_yasg需要与django.contrib.staticfiles配套使用,一般情况下,项目创建都会在INSTALLED_APPS列表中注册这个工具,如果没有,需要手动添加

在settings.py最后面添加下面代码

python 复制代码
# ====================================#
# ****************swagger************#
# ====================================#
SWAGGER_SETTINGS = {
    # 基础样式
    "SECURITY_DEFINITIONS": {"basic": {"type": "basic"}},
    # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的.
    "LOGIN_URL": "apiLogin/",
    # 'LOGIN_URL': 'rest_framework:login',
    "LOGOUT_URL": "rest_framework:logout",
    # 'DOC_EXPANSION': None,
    # 'SHOW_REQUEST_HEADERS':True,
    # 'USE_SESSION_AUTH': True,
    # 'DOC_EXPANSION': 'list',
    # 接口文档中方法列表以首字母升序排列
    "APIS_SORTER": "alpha",
    # 如果支持json提交, 则接口文档中包含json输入框
    "JSON_EDITOR": True,
    # 方法列表字母排序
    "OPERATIONS_SORTER": "alpha",
    "VALIDATOR_URL": None,
    "AUTO_SCHEMA_TYPE": 2,  # 分组根据url层级分,0、1 或 2 层
    "DEFAULT_AUTO_SCHEMA_CLASS": "apps.utils.swagger.CustomSwaggerAutoSchema",
}

3、 如下图usrl.py全文

python 复制代码
from django.urls import path, include, re_path

from drf_yasg import openapi
from drf_yasg.views import get_schema_view
# 导入权限控制模块
from rest_framework import permissions
from apps.utils.swagger import CustomOpenAPISchemaGenerator

schema_view = get_schema_view(
    openapi.Info(
        title="SmartWater API",
        default_version="v1",
        description="smartwater 接口文档",
        terms_of_service="https://www.google.com/policies/terms/",
        contact=openapi.Contact(email="123@qq.com"),
        license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
    generator_class=CustomOpenAPISchemaGenerator,
)
urlpatterns = [
    re_path(
        r"^swagger(?P<format>\.json|\.yaml)$",
        schema_view.without_ui(cache_timeout=0),
        name="schema-json",
    ),
    path(
        "",
        schema_view.with_ui("swagger", cache_timeout=0),
        name="schema-swagger-ui",
    ),
    path(
        r"redoc/",
        schema_view.with_ui("redoc", cache_timeout=0),
        name="schema-redoc",
    ),
    re_path(
        r"^api-auth/", include("rest_framework.urls", namespace="rest_framework")
    ),
]

注意目录

4、添加swagger.py文件

注意目录

代码:

python 复制代码
from drf_yasg.generators import OpenAPISchemaGenerator
from drf_yasg.inspectors import SwaggerAutoSchema

from smartwater.settings import SWAGGER_SETTINGS


def get_summary(string):
    if string is not None:
        result = string.strip().replace(" ","").split("\n")
        return result[0]


class CustomSwaggerAutoSchema(SwaggerAutoSchema):
    def get_tags(self, operation_keys=None):
        tags = super().get_tags(operation_keys)
        if "api" in tags and operation_keys:
            #  `operation_keys` 内容像这样 ['v1', 'prize_join_log', 'create']
            tags[0] = operation_keys[SWAGGER_SETTINGS.get('AUTO_SCHEMA_TYPE', 2)]
        return tags

    def get_summary_and_description(self):
        summary_and_description = super().get_summary_and_description()
        summary = get_summary(self.__dict__.get('view').__doc__)
        description = summary_and_description[1]
        return summary,description


class CustomOpenAPISchemaGenerator(OpenAPISchemaGenerator):
    def get_schema(self, request=None, public=False):
        """Generate a :class:`.Swagger` object with custom tags"""

        swagger = super().get_schema(request, public)
        swagger.tags = [
            {
                "name": "token",
                "description": "认证相关"
            },
        ]
        return swagger

三、测试一下

python manage.py runserver 127.0.0.1:8000

没有写view,所以东西没有

相关推荐
u0109272715 小时前
RESTful API设计最佳实践(Python版)
jvm·数据库·python
我材不敲代码8 小时前
Python实现打包贪吃蛇游戏
开发语言·python·游戏
0思必得011 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
韩立学长11 小时前
【开题答辩实录分享】以《基于Python的大学超市仓储信息管理系统的设计与实现》为例进行选题答辩实录分享
开发语言·python
qq_1927798711 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u01092727111 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊11 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
Imm77712 小时前
中国知名的车膜品牌推荐几家
人工智能·python
tudficdew12 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd65212 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python