flask-restx notes
文章目录
教程
namespace
- 作用:对 Resource 分组
- 参考:API — Flask-RESTX documentation–Namspace class
调用
1api.namespace(...)
Model
参考:
parameters 字段
Parameters: default – The default value for the field, if no value is specified. attribute – If the public facing value differs from the internal value, use this to retrieve a different attribute from the response than the publicly named value. title (str) – The field title (for documentation purpose) description (str) – The field description (for documentation purpose) required (bool) – Is the field required ? readonly (bool) – Is the field read only ? (for documentation purpose) example – An optional data example (for documentation purpose) mask (callable) – An optional mask function to be applied to output
调用
1 2 3 4todo = api.model('Todo', { 'id': fields.Integer(readonly=True, description='The task unique identifier'), 'task': fields.String(required=True, description='The task details') })
api.model
作用
- 工厂函数
完成功能
- 自动把生成的 Model 注册和缓存到 api.models (一个 dict) 中
api.clone
- 复制 给定 model 的 属性,注册新生成的 Model 到 api.models
api.inherit
序列化
参考:
fileds 参数
- 可以是 dict 对象
可以是 Model 对象
- 一个 fields 的包裹工具
marshal
- 作用对象:dict
根据模板序列化
- 先过滤,再序列化
- 类型不符合 –> 报错
调用
1marshal(data, fields, ...)例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14from flask_restx import fields, marshal marshal({'name': 'lucy', 'pro': 'teacher', 'score': 80}, {'name': fields.String, 'pro': fields.String}) # 正常 # 输出 {'name': 'lucy', 'pro': 'teacher'} # * 错误,类型不符 marshal({'name': 'lucy', 'pro': 'teacher', 'score': 80}, {'name': fields.String, 'pro': fields.Float}) # --> pro: fields.Float # ==> 报错 MarshallingError
marshell_with
- 作用对象:return 返回值
参考:
特殊参数
as_list
- 声明返回值是 List
- 这是 fields 指定的是 元素的类型
调用
1 2 3@marshal_with(fields) def your_method(): ...
marshal_with_field
- 用法:类似 typing, 修饰返回值
调用
1 2 3 4 5 6 7>>> from flask_restx import marshal_with_field, fields >>> @marshal_with_field(fields.List(fields.Integer)) ... def get(): ... return ['1', 2, 3.0] ... >>> get() [1, 2, 3]
marshal_list_with
- 即 api.marshal_with(fileds, …, as_list=True)
Swagger Documentation
api.doc
- 提供额外信息
response 类型解说
api.marshal_with
api.marshal_list_with
request 类型解说
api.expect
- 参考:Swagger documentation — Flask-RESTX 0.4.1.dev documentation
可选参数
validate: bool
- 是否验证输入 request
调用
- 输入 list
| |
解说
- 只需 把 fields 写成 [fields] 即可
fields
类型
- fields.String
- fields.Url
- fileds.Boolean
- fileds.Integer
- fileds.Float
fileds.Arbitray
- 任意精度 float
- List
- …
Mask
作用
- 只选用 给定 Model 中的有限个 fields
- 参考:Fields masks — Flask-RESTX 0.4.1.dev documentation
调用
1 2 3 4 5model = api.model('Person', { 'name': fields.String, 'age': fields.Integer, 'boolean': fields.Boolean, }, mask='{name,age}')- 这里 只选用 name 和 age 字段
嵌套字段的 mask
1mask = '{name, age, pet{name}}'解释
- json 有字段 name, age, pet
- pet 字段有 pet 属性
内层字段制定
1mask = '{pets{name},*}'解释
- 只有 pets 内部属性,只选用 name 属性
- 其他外层字段,无过滤,全部选用
实例
| |
文章作者
上次更新 2023-02-10 (97c415e)