翻译说明
文档基于DeepL.com 翻译,人工纠错.
flask-smorest官方文档
简介
flask-smorest: 基于Flask/Marshmallow的REST API框架
flask-smorest(原名为flask-rest-api)是一个用于创建于数据库无关的REST API的架库。
它使用Flask作为Web服务器,并使用marsmallow对数据进行序列化和反序列化。它广泛依赖marsmallow生态系统,使用webargs从请求中获取参数,并使用apispec尽可能自动生成一个OpenAPI规范文件。
安装
flask-smorest 需要 Python >= 3.5.$ pip install flask-smorest
指南
快速入门
介绍
flask-smorest对代码应该如何结构化做了一些设定。
应用程序应该在Blueprint中进行拆分。可以使用基本的Flask视图函数,但通常最好使用Flask MethodView。
Marshmallow Schema被用来序列化参数和响应。
请求和响应体被序列化为JSON。
一个视图函数只有一个成功的响应类型和状态代码。所有其他可能的响应都是错误。
示例
下面是一个基本的 “宠物商店例子”,其中Pet类是一个虚构的ORM。
首先用Flask应用程序实例化一个Api。
from flask import Flaskfrom flask.views import MethodViewimport marshmallow as mafrom flask_smorest import Api, Blueprint, abortfrom .model import Petapp = Flask('My API')app.config['OPENAPI_VERSION'] = '3.0.2'api = Api(app)
定义一个marshmallow Schema类来输出model
class PetSchema(ma.Schema):id = ma.fields.Int(dump_only=True)name = ma.fields.String()
定义一个marshmallow Schema 类来验证查询参数
class PetQueryArgsSchema(ma.Schema):
name = ma.fields.String()
实例化一个蓝图(Blueprint)
blp = Blueprint('pets', 'pets', url_prefix='/pets',description='Operations on pets')
使用MethodView类来组织资源(resources),用Blueprint.arguments和Blueprint.response来装饰视图方法,指定请求反序列化和响应序列化。
使用abort返回错误,传递错误处理程序(handle_http_exception)使用的kwargs来建立错误响应。。
@blp.route('/')class Pets(MethodView):@blp.arguments(PetQueryArgsSchema, location='query')@blp.response(PetSchema(many=True))def get(self, args):"""List pets"""return Pet.get(filters=args)@blp.arguments(PetSchema)@blp.response(PetSchema, code=201)def post(self, new_data):"""Add a new pet"""item = Pet.create(**new_data)return item@blp.route('/<pet_id>')class PetsById(MethodView):@blp.response(PetSchema)def get(self, pet_id):"""Get pet by ID"""try:item = Pet.get_by_id(pet_id)except ItemNotFoundError:abort(404, message='Item not found.')return item@blp.arguments(PetSchema)@blp.response(PetSchema)def put(self, update_data, pet_id):"""Update existing pet"""try:item = Pet.get_by_id(pet_id)except ItemNotFoundError:abort(404, message='Item not found.')item.update(update_data)item.commit()return item@blp.response(code=204)def delete(self, pet_id):"""Delete pet"""try:Pet.delete(pet_id)except ItemNotFoundError:abort(404, message='Item not found.')
最后,在API中注册蓝图
api.register_blueprint(blp)