flask openapi(swagger) doc generator
Project description
flask-siwadoc
flask-siwadoc 是一个兼具数据校验和openapi(swagger)文档自动生成的项目
特性
0、零配置
接入flask-siwadoc无需任何配置
1、数据校验
flask-siwadoc 站在巨人肩膀上,数据校验利用pydantic强大的数据验证功能,支持请求查询参数和请求体参数的数据校验及转换功能。因此本项目同时依赖于pydantic。
2、接口文档自动生成
接口文档生成只需要简单初始化一个siwa=SiwaDoc(app),利用装饰器 siwa.doc()修饰flask的视图函数,即可将该视图函数加入openapi的接口文档规范中。
3、ui切换
flask-siwadoc内置了redoc和swagger两种UI 界面,通过参数/docs/?ui=swagger切换
4、文档支持分组与标签
安装
pip install flask-siwadoc
快速开始
example 1
from flask import Flask
from flask_siwadoc import SiwaDoc
app = Flask(__name__)
siwa = SiwaDoc(app)
# or
# siwa.init_app(app)
@app.route("/hello", methods=["GET"])
@siwa.doc()
def hello():
return "hello siwadoc"
if __name__ == '__main__':
app.run()
运行后,访问 http://127.0.0.1:5000/docs 就可以看到openapi的文档页面
example 2:指定查询参数 query
from pydantic import BaseModel, Field
class QueryModel(BaseModel):
page: int = Field(default=1, title="current page number")
size: int = Field(default=20, title="size of page", ge=10, le=100)
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=['user'])
def users_list():
"""
user list
"""
return [{"username": "siwa", "id": 1}]
对于数查询接口,GET请求需如果有查询参数,得益于pydantic强大的类型功能,我们只需要一个继承了BaseModel的自定义类,即可实现数据校验及转换。
如何在视图函数中使用该query这个对象呢? 有两种方式
方式一:
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello():
print(request.query.keyword)
return "hello"
flask-siwadoc 将QueryModel的实例对象query绑定到了flask的request对象上,不过对开发者来说使用并不友好,你没法知道它的类型是什么,意味着IDE无法用.的方式调出该实例的属性。
方式二:(推荐方式)
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello(query: QueryModel):
print(query.keyword)
return "hello"
将query变量作为视图函数的参数,flask-siwadoc 会自动将QueryModel实例对象赋值给query变量,因为我们这里给query指定了类型声明,因此通过IDE可以很方便的调出实例属性。
下面的example3中的body参数原理也是类似的。
example3 :指定请求体 body
class LoginModel(BaseModel):
username: str
password: str
@app.route("/login", methods=["POST"])
@siwa.doc(body=LoginModel)
def login(body: LoginModel):
return {"username": body.username, "id": 1}
对于POST请求,请求体是基于application/json 类型, 会自动转换成LoginModel类型的对象,就可以用静态语言一样,通过点选的方式调出属性,例如 body.username
example4: 指定返回体 resp
class UserModel(BaseModel):
id: int
username: str
@app.route("/users/1", methods=["GET"])
@siwa.doc(resp=UserModel)
def users():
"""
user detail
"""
return {"username": "siwa", "id": 1}
example5: 指定标签分类 tags
项目中如果接口太多,我们可以对接口根据业务划分不同的模块标签来分类管理。
@siwa.doc(resp=UserModel, tags=["user"])
指定tags参数,tags参数是一个列表,一个接口可支持多个标签。
example6:路径参数也支持文档化
针对参数,除了请求查询参数和请求体参数外,url路径中的参数,例如/users/<int(min=1):user_id> 同样支持,对于路径参数转api文档参数,不需要开发者做额外的处理,flask-siwadoc内部已经做了处理。
class QueryModel(BaseModel):
gender: str
class UpdatePasswordModel(BaseModel):
password: str
@app.route("/users/<int(min=1):user_id>", methods=["POST"])
@siwa.doc(query=QueryModel, body=UpdatePasswordModel, resp=UserModel)
def update_password(user_id):
"""
update password
"""
return {"username": "siwa", "id": user_id}
完整示例可参考 example.py
UI切换
文档默认使用redoc进行渲染,你可以通过指定参数ui=swaggerui显式文档。
http://127.0.0.1:5000/docs/?ui=swagger
扩展
如果数据校验报错,flask-siwadoc 会抛出异常flask_siwadoc.error.ValidationError,ValidationError 继承自pydantic.ValidationError
例如:
class QueryModel(BaseModel):
keyword: str
@app.route("/users", methods=["GET"])
@siwa.doc(query=QueryModel, tags=["user"])
def hello(query: QueryModel):
print(query)
return "hello"
该接口中,keyword是必选的查询参数,如果url中没有keyword参数,就会抛出异常
raise ValidationError(e)
flask_siwadoc.error.ValidationError: 2 validation errors for Auth
username
field required (type=value_error.missing)
password
field required (type=value_error.missing)
我们需要通过使用flask的 errorhandler() 装饰函数来注册ValidationError错误,这样错误异常就可以被validate_error函数捕获,开发者可以给前端直接一个友好的错误响应体
@app.errorhandler(ValidationError)
def validate_error(e: ValidationError):
return dict(code=-1, msg="请求参数错误", error_info=e.errors()), 400
reference
- https://pydantic-docs.helpmanual.io/
- https://github.com/bauerji/flask-pydantic
- https://github.com/kemingy/flaskerk
任何问题欢迎发issue或者加我微信 lzjun567 交流,欢迎PR
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file flask-siwadoc-0.0.4.tar.gz.
File metadata
- Download URL: flask-siwadoc-0.0.4.tar.gz
- Upload date:
- Size: 14.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.9.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
996dfd9d4912f8b9ef541e46bf5cd2803424f19978355731cd931cfcf2ec5b87
|
|
| MD5 |
fbc09f819df8b138710e2e2e4c830636
|
|
| BLAKE2b-256 |
1b9d982437931d24c695149ee4294479e80853bfdef2ff1a695a8707e38177ed
|
File details
Details for the file flask_siwadoc-0.0.4-py3-none-any.whl.
File metadata
- Download URL: flask_siwadoc-0.0.4-py3-none-any.whl
- Upload date:
- Size: 12.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.1 CPython/3.9.2
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cf7230bef67b40ed65f94df3c9e353a9a161a6d8c340f5c521a68977ba9e6899
|
|
| MD5 |
f702aecc0ee5a4ea3fa1f2a77eb6bee6
|
|
| BLAKE2b-256 |
e34b47b3b1916c82e7c11d2631c7a90b415cb24533578b359f727567de6deb85
|