关于drf_yasg Api定制软件文档使用示例
配置
-
settings.py
INSTALLED_APPS = [ ... 'drf_yasg', ... ] ```
- 1
- 2
- 3
- 4
- 5
- 6
- 7
-
urls.py
from rest_framework import permissionsfrom drf_yasg.views import get_schema_viewfrom drf_yasg import openapischema_view = get_schema_view( openapi.Info( title="平台API文档", default_version='v1', description="Welcome to ***", # terms_of_service="https://www.tweet.org", # contact=openapi.Contact(email="demo@tweet.org"), # license=openapi.License(name="Awesome IP"), ), public=True, # 定制软件我也添加了此处但是还定制软件是有权限问题 permission_classes=(permissions.AllowAny,),)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
# 定制软件对测试人员更友好path('doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # 定制软件对开发人员更友好path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
- 1
- 2
- 3
- 4
-
定制软件验证权限问题 定制软件测试的时候报403
方法1:#定制软件注释掉此处就可访问到文档REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ['user_profile.utils.auth.CustomAuthentication', ],}
- 1
- 2
- 3
- 4
方法2:对doc创建一个验证类
class DRFdocAuthentication(BaseAuthentication): def authenticate(self, request): token_obj = models.UserToken.objects.first() return token_obj.user, token_obj def authenticate_header(self, request): pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
然后在该处添加此行,即可正常访问
get_schema_view( public=True, # 添加此行 authentication_classes=(DRFdocAuthentication,))
- 1
- 2
- 3
- 4
- 5
api文档编写使用
from drf_yasg.utils import swagger_auto_schemaclass PolygonView(APIView): # 使用该装饰器 @swagger_auto_schema() def get(self, request, generate_id): pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
装饰器使用前介绍
查看drf_yasg.openapi模块中的 20-56行,介绍了 type,format,in_三个参数的类型,他们值都进行了常量化 type有: "object" ,"string" ,"number" ,"integer" ,"boolean" ,"array" ,"file" format有: date,date-time,password,binary,bytes,float,double,int32,int64,email, ipv4,ipv6,uri,uuid,slug,decimal等类型 in_参数(代表参数在什么位置)有: body,path,query,formData,header Parameter:用来构造请求参数 Schema:对参数进行补充说明,属性说明等 Response:用来构造单个响应数据的 比如200状态码对应的响应 Responses:用来构造多个响应数据的 {200:正常响应,401:验证未通过响应}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
swagger_auto_schema使用
def swagger_auto_schema( method=None, # 单个请求方法 GET 类方法下不需要 methods=None, # 请求方法的列表 ['GET','POST'] 类方法下不需要 auto_schema=unset, request_body=None, # 请求体 Schema对象 query_serializer=None, # serializer类 manual_parameters=None, # 参数列表 [Parameter对象列表] 可以通过in_=IN_PATH,来修饰path中的参数 operation_id=None, # API的唯一编号 可以不填 operation_description=None, # 对该API的描述信息 operation_summary=None, security=None, deprecated=None, # 是否弃用 responses=None, # 响应体 {200:Response对象,401:serializer类} dict[int or str, (drf_yasg.openapi.Schema or drf_yasg.openapi.SchemaRef or drf_yasg.openapi.Response or str or rest_framework.serializers.Serializer)] field_inspectors=None, filter_inspectors=None, paginator_inspectors=None, tags=None, # 模块名称 **extra_overrides):
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
Parameter使用
class Parameter(SwaggerDict): def __init__(self, name, in_, description=None, required=None, schema=None, type=None, format=None, enum=None, pattern=None, items=None, default=None, **extra): name:参数名称 in_:参数位置 参见 装饰器使用前介绍 部分 description:参数描述 required:是否必须 schema:当in_是body时,schema对象 type:类型 参见 装饰器使用前介绍 部分 format:格式 参见 装饰器使用前介绍 部分 enum:(列表) 列举参数的请求值(请求值只在这几个值中) pattern:当 format为 string是才填此项 items: default:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
使用
class Schema(SwaggerDict): def __init__(self, title=None, description=None, type=None, format=None, enum=None, pattern=None, properties=None,additional_properties=None, required=None, items=None, default=None, read_only=None, **extra): title:标题(可以不填)description:描述type:类型 参见 装饰器使用前介绍 部分format:格式 参见 装饰器使用前介绍 部分enum:(列表) 列举参数的请求值(请求值只在这几个值中)pattern:当 format为 string是才填此项properties: 当 type为object时,为dict对象{'str1':Schema对象,'str2':SchemaRef对象}required:[必须的属性列表]items:当type是array时,填此项default:
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
Response使用
class Response(SwaggerDict): def __init__(self, description, schema=None, examples=None, **extra): description:字符串 schema:Schema对象 examples:dict对象
- 1
- 2
- 3
- 4
- 5
PUT请求示例
polygon_view_put_desc='根据generate_id修改一个图斑' polygon_view_put_parm=Schema(type=TYPE_OBJECT,properties={ 'reason':Schema(description='变化原因 example: 造林更新',type=TYPE_STRING), 'village':Schema(description='所属乡镇 example: 石马镇',type=TYPE_STRING), 'remarks':Schema(description='备注 example: ...',type=TYPE_STRING), 'real_area':Schema(description='实测面积 example: 2020',type=TYPE_NUMBER), 'disguise_change':Schema(description='是否是伪变化 example: 0表示不是,1 表示是',type=TYPE_INTEGER,enum=[0,1]), 'images':Schema(description='上传图片id列表 example: [1,2,3]',type=TYPE_ARRAY,items=Schema(type=TYPE_INTEGER)),# 列表对象 }) polygon_view_put_resp={200:Response(description='修改成功',examples={'json':{'msg': '修改成功!', "data": []}})} @swagger_auto_schema(operation_description=PSW.polygon_view_put_desc,request_body=PSW.polygon_view_put_parm,responses=PSW.polygon_view_put_resp)def put(self, request, generate_id): pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
-
请求参数效果图:
-
响应效果:
GET请求示例
polygon_view_get_desc='根据generate_id获取 返回一个图斑'polygon_view_get_parm=[ Parameter(name='generate_id',in_=IN_PATH,description='图斑id example:20201212125560555',type=TYPE_STRING,required=True),Parameter(name='year',in_=IN_QUERY,description='年份 example: 2020',type=TYPE_INTEGER,required=False),Parameter(name='quarter', in_=IN_QUERY, description='季度 例如:1 代表一季度', required=False,type=TYPE_INTEGER,enum=[1,2,3,4,5]),]polygon_view_get_resp={200:DiffPolygonSerializer}@swagger_auto_schema(operation_description=PSW.polygon_view_get_desc,manual_parameters=PSW.polygon_view_get_parm,responses=PSW.polygon_view_get_resp)def get(self, request, generate_id): pass
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
-
效果图:
-
响应结果