西麦农场

时间尺度守恒


  • 首页

  • 分类

  • 归档

  • 坑List

flask-smorest 中文文档

2020-04-23 | 文档 | Flask RESTful API Marshmallow

翻译说明

文档基于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。

  1. from flask import Flask
  2. from flask.views import MethodView
  3. import marshmallow as ma
  4. from flask_smorest import Api, Blueprint, abort
  5. from .model import Pet
  6. app = Flask('My API')
  7. app.config['OPENAPI_VERSION'] = '3.0.2'
  8. api = Api(app)

定义一个marshmallow Schema类来输出model

  1. class PetSchema(ma.Schema):
  2. id = ma.fields.Int(dump_only=True)
  3. name = ma.fields.String()

定义一个marshmallow Schema 类来验证查询参数
class PetQueryArgsSchema(ma.Schema):
name = ma.fields.String()

实例化一个蓝图(Blueprint)

  1. blp = Blueprint(
  2. 'pets', 'pets', url_prefix='/pets',
  3. description='Operations on pets'
  4. )

使用MethodView类来组织资源(resources),用Blueprint.arguments和Blueprint.response来装饰视图方法,指定请求反序列化和响应序列化。

使用abort返回错误,传递错误处理程序(handle_http_exception)使用的kwargs来建立错误响应。。

  1. @blp.route('/')
  2. class Pets(MethodView):
  3. @blp.arguments(PetQueryArgsSchema, location='query')
  4. @blp.response(PetSchema(many=True))
  5. def get(self, args):
  6. """List pets"""
  7. return Pet.get(filters=args)
  8. @blp.arguments(PetSchema)
  9. @blp.response(PetSchema, code=201)
  10. def post(self, new_data):
  11. """Add a new pet"""
  12. item = Pet.create(**new_data)
  13. return item
  14. @blp.route('/<pet_id>')
  15. class PetsById(MethodView):
  16. @blp.response(PetSchema)
  17. def get(self, pet_id):
  18. """Get pet by ID"""
  19. try:
  20. item = Pet.get_by_id(pet_id)
  21. except ItemNotFoundError:
  22. abort(404, message='Item not found.')
  23. return item
  24. @blp.arguments(PetSchema)
  25. @blp.response(PetSchema)
  26. def put(self, update_data, pet_id):
  27. """Update existing pet"""
  28. try:
  29. item = Pet.get_by_id(pet_id)
  30. except ItemNotFoundError:
  31. abort(404, message='Item not found.')
  32. item.update(update_data)
  33. item.commit()
  34. return item
  35. @blp.response(code=204)
  36. def delete(self, pet_id):
  37. """Delete pet"""
  38. try:
  39. Pet.delete(pet_id)
  40. except ItemNotFoundError:
  41. abort(404, message='Item not found.')

最后,在API中注册蓝图

  1. api.register_blueprint(blp)
  • 目录
  • 站点概览
  • 翻译说明
  • 简介
    • 安装
  • 指南
    • 快速入门
      • 介绍
      • 示例
    戊在西安填坑中

    戊在西安填坑中

    29 日志
    7 分类
    50 标签
    0%
    © 2017- 戊在西安填坑中 | 陕ICP备13008306号-3 | 主题 NexT.Pisces