flask_smorest

2022-08-09  本文已影响0人  Andy_1ee

文档地址:https://flask-smorest.readthedocs.io/en/latest/index.html

1. 这个包是干什么的

2. 使用

1. 安装

pip install flask_smorest

2. 基本使用
# main.py
from flask_smorest import Api, Blueprint as APIBlueprint
from flask import Flask

app = Flask(__name__)
api = Api(app)


# blp.py
from flask_smorest import  Blueprint as APIBlueprint
from flask.views import MethodView

blp = APIBlueprint("pets", __name__, url_prefix="/pets", description="Operations on pets")
@blp.route('/')
class Pet(MethodView):
    @blp.arguments(<marshmallow_deserialize_schema>, location=<default: json>)
    @blp.response(<marshmallow_serialize_schema>)
    def get(args):
        ...
        return Pet().get_all(args)

ps: argument及response 装饰器用来装饰 类方法
ps2: argument 装饰器可以堆叠, 用来读取多个位置传入的数据

3. Arguments 参数解析

1. <marshmallow_deserialize_schema> : 基于marshmallow 的 反序列化和校验类
2. location: [json, query, path, form, headers, cookie, files], 默认 json, 选择读取的参数位置
3. as_kwargs: <boolen>,  默认false, 如果为true, 则会使用关键字参数传入函数, 默认用字典传入函数

4. Response 参数解析

1. <marshmallow_serialize_schema>: 基于marshmallow的序列化类, 如果是多条数据, 需要设置many=True
2. code: 默认200

5. Pagination 分页

@blp.route("/")
class Pets(MethodView):
    @blp.response(200, PetSchema(many=True))
    @blp.paginate()
    def get(self, pagination_parameters):
        pagination_parameters.item_count = Pet.size
        return Pet.get_elements(
            first_item=pagination_parameters.first_item,
            last_item=pagination_parameters.last_item,
        )

初步判断这是一种通过全部获取后 再进行分页的方式

上一篇 下一篇

猜你喜欢

热点阅读