智慧水务项目(四)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,所以东西没有

相关推荐
我命由我1234517 分钟前
访客系统形式(有用户概念、无用户概念)
java·开发语言·前端·javascript·python·产品运营·产品经理
xixingzhe232 分钟前
图表中同比与环比的区别:看趋势还是看变化?
开发语言·python
forest_091 小时前
当 AI 搜索开始「自我进化」,谁来进化它的核实?——「已核实」结论复核器:3 条结论挖出 2 个洞(附可运行代码)
人工智能·python·机器学习·prompt·agi
小小张说故事1 小时前
Python 的 str 为什么设计成不可变?拆开字符串驻留、字符串池,以及 += 拼接到底慢在哪
后端·python
ljt27249606611 小时前
Python笔记(十一)--Numpy(一)
笔记·python·numpy
时早玖沐1 小时前
KOOK「找不到语音频道」:同一个错误假设,我犯了三次
python·开源·ai编程
_冷眸_1 小时前
Python 调用大模型 API:最小请求、Base URL 和 401/404 排查
开发语言·人工智能·python
AI架构师之家1 小时前
我把 Hermes 这匹"马"养了两周,它干了一件让我有点发毛的事
后端
dpharness1 小时前
块协议用了两周,我把九个坑按顺序记下来了
后端
加宝的起点雷达2 小时前
跑了两周的信号日报,我把降级链改了四次
人工智能·后端