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

avatar
作者
筋斗云
阅读量:0

一、说明

文档api接口是必须的

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

二、步骤

1、requirements.txt添加drf-yasg

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

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

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

# ====================================# # ****************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全文

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文件

注意目录

 

代码:

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,所以东西没有 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!