Flask-RESTPlus 中文文档(Flask-RESTPlus Chinese document)

本文档是Flask-RESTPlus的文档中文翻译版,英文原版地址:https://flask-restplus.readthedocs.io/en/stable/

相关信息

  • 文档对应版本:0.13.0 stable
  • 本文档是个人翻译版本,非官方翻译版,一切内容以官方英文原版为准。
  • 本文档与Flask-RESTPlus开发组无任何关系,提交bug等开发问题请移步项目所在地:https://github.com/noirbizarre/flask-restplus
  • 部分翻译内容可能并不准确,没把握的地方我都标记了原文
  • 文档采用Typora编写,推荐使用Typora进行查看

鸣谢

开源许可

目录

提示:

部分无法跳转的目录是由于未完成翻译,如果目录有误请另开issue反馈。

提示:

目录是为了方便Github在线观看使用,部分目录在Typora中是不可用的,下载用户请使用Typora自带的大纲功能。

安装

使用 pip安装Flask-RESTPlus:

  1. pip install flask-restplus

开发版可以从 Github 上下载:

  1. git clone https://github.com/noirbizarre/flask-restplus.git
  2. cd flask-restplus
  3. pip install -e .[dev,test]

Flask-RESTPlus需要python 2.7, 3.3, 3.4 或 3.5支持。当然PyPy和PyPy3同样适用。

快速开始

本文档需要你对 Flask 的工作机制有所了解,同时请确保你已完成了Flask与Flask-RESTPlus的安装工作。如果没有完成安装,请参阅 安装

初始化

和其他Flask扩展一样,你可以用 applicaiton 对象初始化它:

  1. from flask import Flask
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. api = Api(app)

或者使用懒加载模式:

  1. from flask import Flask
  2. from flask_restplus import Api
  3. api = Api()
  4. app = Flask(__name__)
  5. api.init_app(app)

一个最小API

一个最小的Flask-RESTPlus API 应该如下所示:

  1. from flask import Flask
  2. from flask_restplus import Resource, Api
  3. app = Flask(__name__)
  4. api = Api(app)
  5. @api.route('/hello')
  6. class HelloWorld(Resource):
  7. def get(self):
  8. return {'hello': 'world'}
  9. if __name__ == '__main__':
  10. app.run(debug=True)

将上述代码保存为 api.py并使用Python解释器运行。值得注意的是我们已经打开了Flask的调试模式(Flask debugging)这将为我们提供代码热重载和更好的报错信息。

  1. $ python api.py
  2. * Running on http://127.0.0.1:5000/
  3. * Restarting with reloader

警告:

调试模式不能用于任何生产环境下!

现在打开一个新窗口测试一下你的API:

  1. $ curl http://127.0.0.1:5000/hello
  2. {"hello": "world"}

你同时可以将自动文档作为你的API根目录(默认是开启的)。在本例子中,根目录为:http://127.0.0.1:5000/ 。查看 Swagger UI 章节获取完整信息。

面向资源(Resource)的路由

Flask-RESTPlus所能提供的主要组件由资源类(Resource)实现。资源类是在 Flask可扩展视图(Flask pluggable views) 的基础上实现的,提供了添加指定函数就能实现多种http访问方法的功能。一个实现代办事项(todo)应用程序的基础CURD(译者:就是增删改查的意思)资源类如下所示:

  1. from flask import Flask, request
  2. from flask_restplus import Resource, Api
  3. app = Flask(__name__)
  4. api = Api(app)
  5. todos = {}
  6. @api.route('/<string:todo_id>')
  7. class TodoSimple(Resource):
  8. def get(self, todo_id):
  9. return {todo_id: todos[todo_id]}
  10. def put(self, todo_id):
  11. todos[todo_id] = request.form['data']
  12. return {todo_id: todos[todo_id]}
  13. if __name__ == '__main__':
  14. app.run(debug=True)

测试一下:

  1. $ curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
  2. {"todo1": "Remember the milk"}
  3. $ curl http://localhost:5000/todo1
  4. {"todo1": "Remember the milk"}
  5. $ curl http://localhost:5000/todo2 -d "data=Change my brakepads" -X PUT
  6. {"todo2": "Change my brakepads"}
  7. $ curl http://localhost:5000/todo2
  8. {"todo2": "Change my brakepads"}

如果你的python安装了 python-requests 你也可以用python进行测试:

  1. >>> from requests import put, get
  2. >>> put('http://localhost:5000/todo1', data={'data': 'Remember the milk'}).json()
  3. {u'todo1': u'Remember the milk'}
  4. >>> get('http://localhost:5000/todo1').json()
  5. {u'todo1': u'Remember the milk'}
  6. >>> put('http://localhost:5000/todo2', data={'data': 'Change my brakepads'}).json()
  7. {u'todo2': u'Change my brakepads'}
  8. >>> get('http://localhost:5000/todo2').json()
  9. {u'todo2': u'Change my brakepads'}

Flask-RESTPlus支持多种函数返回值。和 Flask 类似,你可以返回任意可迭代的对象(iterable)包括原生 Flask 响应对象(raw Flask response objects)而它们会被转化成响应(response)。Flask-RESTPlus同样支持使用多个返回值自定义状态码(response code)和响应头(response headers),示例如下:

  1. class Todo1(Resource):
  2. def get(self):
  3. # Default to 200 OK
  4. return {'task': 'Hello world'}
  5. class Todo2(Resource):
  6. def get(self):
  7. # Set the response code to 201
  8. return {'task': 'Hello world'}, 201
  9. class Todo3(Resource):
  10. def get(self):
  11. # Set the response code to 201 and return custom headers
  12. return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}

端点(Endpoint)

在很多情况下,一个API中,你的一个资源类可能需要对应多个url地址。你可以传入多个url地址到 add_resource() 函数中或者使用 route() 装饰器,这两个方法都由Api对象提供。其中这的任意一个方法都能实现多url路由到你的资源类上:

  1. api.add_resource(HelloWorld, '/hello', '/world')
  2. # or
  3. @api.route('/hello', '/world')
  4. class HelloWorld(Resource):
  5. pass

同时你也可以将一部分匹配路径作为变量传入你的资源类函数中:

  1. api.add_resource(Todo, '/todo/<int:todo_id>', endpoint='todo_ep')
  2. # or
  3. @api.route('/todo/<int:todo_id>', endpoint='todo_ep')
  4. class HelloWorld(Resource):
  5. pass

提示:

如果请求无法匹配应用程序中的任何端点,Flask-RESTPlus 会返回404错误信息并附带最接近请求的端点猜测。你可以在配置文件中将 ERROR_404_HELP改为False来禁用这个功能。

参数解析

虽然 Flask 提供了很方便的途径访问请求数据(如:请求参数(querystring)或 POST表单数据(POST form encoded data)),但是验证表单数据依然很麻烦。Flask-RESTPlus提供了内置的表单验证功能,具体由一个类似于 argparse 的库完成。

  1. from flask_restplus import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('rate', type=int, help='Rate to charge for this resource')
  4. args = parser.parse_args()

提示:

argparse 不同的是,parse_args() 返回的是一个Python字典对象,而不是一个自定义的数据结构

使用 RequestParser类同时也可以自动给你提供清晰的错误信息。如果一个参数在验证过程中出现问题,Flask-RESTPlus 将返回一个400错误并高亮错误。

  1. $ curl -d 'rate=foo' http://127.0.0.1:5000/todos
  2. {'status': 400, 'message': 'foo cannot be converted to int'}

input模块提供了大量转化函数,如 date()url()

调用 parse_args() 时附带参数 stict=True,程序将在表单中出现解析器(parser)未定义的参数时抛出异常。

  1. args = parser.parse_args(strict=True)

数据格式化

在默认情况下,你返回的所有可迭代对象将会被按照原样呈现。在针对Python原生数据结构时这种策略能够很好的完成任务,但是在处理对象时效果令人沮丧。为了解决这个问题,Flask-RESTPlus 提供了 字段(Field)模块和 marshal_with()装饰器。和 Django ORM 与 WTForm 类似,你可以使用 字段(fields)模块来定义你的响应数据结构。

  1. from collections import OrderedDict
  2. from flask import Flask
  3. from flask_restplus import fields, Api, Resource
  4. app = Flask(__name__)
  5. api = Api(app)
  6. model = api.model('Model', {
  7. 'task': fields.String,
  8. 'uri': fields.Url('todo_ep')
  9. })
  10. class TodoDao(object):
  11. def __init__(self, todo_id, task):
  12. self.todo_id = todo_id
  13. self.task = task
  14. # This field will not be sent in the response
  15. self.status = 'active'
  16. @api.route('/todo')
  17. class Todo(Resource):
  18. @api.marshal_with(model)
  19. def get(self, **kwargs):
  20. return TodoDao(todo_id='my_todo', task='Remember the milk')

上面的例子我们拿了一个Python对象并准备将其序列化。 marlshal_with() 装饰器将会将其通过 model进行转化。 fields.Url 字段是个很特别的字段,他将选取一个端点在响应中生成带该端点的URL。使用 marlshal_with() 同时也会为文档添加Swagger格式的文档内容。大部分字段类型已经预定义过。查看 字段(fields)导航获取完整列表。

指令保存

在默认情况下,字段指令(fields order)并不会被保存,因为这将影响性能。如果你任然希望字段指令被保存,你可以通过添加参数 ordered=True在某些类或者函数上进行强制保存:

  • Api上全局设置:api = Api(ordered=True)

  • 命名空间(Namespace) 上全局设置:ns = Namespace(ordered=True)

  • 使用 marshal() 局部设置:return marshal(data, fields, ordered=True)

响应编组

Flask-RESTPlus提供了一种很简单的方法去控制你响应的渲染内容或控制实际输入与期望输入相同(expect as in input payload)。通过 字段(fields) 模块,你可以在你的资源类中使用任何的对象(ORM 模型、自定义的类……)。 字段(fields) 同时能帮助你格式化和过滤请求,因此你将不需要担心会暴露内部的数据结构。

同时这也将提高代码的可读性,你可以轻易的看出哪些数据会被渲染哪些数据会被格式化输出。

基础用法

你可以定义一个字典(dict)或有序字典(OrderedDict)来存放其键的属性名称或要渲染的对象上的键的字段,并且其值是将格式化并返回该字段的值的类。下面的例子有三个字段:2个是 String ,1个是 DateTimeDateTime 将被格式化为ISO 8601日期时间字符串(ISO 8601 datetime string)(当然RFC 822也是支持的):

  1. from flask_restplus import Resource, fields
  2. model = api.model('Model', {
  3. 'name': fields.String,
  4. 'address': fields.String,
  5. 'date_updated': fields.DateTime(dt_format='rfc822'),
  6. })
  7. @api.route('/todo')
  8. class Todo(Resource):
  9. @api.marshal_with(model, envelope='resource')
  10. def get(self, **kwargs):
  11. return db_get_todo() # Some function that queries the db

在这个例子里面你有一个自定义的数据库对象(todo),它拥有 nameaddressdate_updated 属性。整个对象的其他附加属性都将是私有的并且不会在输出中渲染。指定了一个可选的 envelope 关键字参数来包装结果输出。

marlshal_with() 修饰器实际上将你的对象做了字段过滤。编组(marlshaling)可以用于单个对象、字典、由对象组成的列表。

提示:

marlshal_with() 是一个很方便的修饰器,它在功能上和下面的代码等同:

  1. class Todo(Resource):
  2. def get(self, **kwargs):
  3. return marshal(db_get_todo(), model), 200

@api.marlshal_with() 添加了Swagger文档的功能。

这种显示的声明可以用于在正常响应时返回一个大于200的HTTP状态码(查看 abort() 获取异常相关信息)。(译者:API并没有翻译,这里是原版的API文档)

重命名属性

很多时候内部字段名和外部的字段名是不一样的。你可以使用 attribute 关键字来配置这种映射关系。

  1. model = {
  2. 'name': fields.String(attribute='private_name'),
  3. 'address': fields.String,
  4. }

attribute 关键字也支持lambda表达式或任何可调用对象。

  1. model = {
  2. 'name': fields.String(attribute=lambda x: x._private_name),
  3. 'address': fields.String,
  4. }

嵌套属性(Nested properties)也可以通过 attribute 进行访问。

  1. model = {
  2. 'name': fields.String(attribute='people_list.0.person_dictionary.name'),
  3. 'address': fields.String,
  4. }

默认值

如果你的数据对象里没有字段列表中对应的属性,你可以指定一个默认值而不是返回一个 None

  1. model = {
  2. 'name': fields.String(default='Anonymous User'),
  3. 'address': fields.String,
  4. }

自定义字段(Custom Fields)& 多个数值

有时候你有自定义格式的需求。你需要继承父类 fields.Raw 并实现 format() 函数。当存储多种信息的时候,这种方法很有用。例如:一个比特类型的字段,其各个位代表不同的值。您可以使用字段将单个属性多路复用到多个输出值。

在这个例子中,flag 属性的第一位代表“正常”或“急迫”,第二位代表“已读”或”未读“。这些东西可以很容易的存入一个比特字段中,但是为了方便人类阅读将其转化成字符串字段是更好的选择。

  1. class UrgentItem(fields.Raw):
  2. def format(self, value):
  3. return "Urgent" if value & 0x01 else "Normal"
  4. class UnreadItem(fields.Raw):
  5. def format(self, value):
  6. return "Unread" if value & 0x02 else "Read"
  7. model = {
  8. 'name': fields.String,
  9. 'priority': UrgentItem(attribute='flags'),
  10. 'status': UnreadItem(attribute='flags'),
  11. }

Url & 其他预定义字段(Other Concrete Fields)

Flask-RESTPlus包含一个特殊字段, fields.Url , 它可以为需求的资源类合成一个URL。这也是一个向响应中添加数据的好例子,而这些数据实际上并不存在于数据对象中。

  1. class RandomNumber(fields.Raw):
  2. def output(self, key, obj):
  3. return random.random()
  4. model = {
  5. 'name': fields.String,
  6. # todo_resource is the endpoint name when you called api.route()
  7. 'uri': fields.Url('todo_resource'),
  8. 'random': RandomNumber,
  9. }

默认情况下,fields.Url 返回的是相对路径。为了生成带有协议(scheme)、主机名和端口的绝对路径,你可以在字段声明时添加 absolute=True 关键字。使用 scheme 关键字来覆盖原本的协议类型。

  1. model = {
  2. 'uri': fields.Url('todo_resource', absolute=True)
  3. 'https_uri': fields.Url('todo_resource', absolute=True, scheme='https')
  4. }

复杂结构

你可以通过 marshal() 函数将平面的数据结构转化成嵌套的数据结构:

  1. >>> from flask_restplus import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> resource_fields = {'name': fields.String}
  5. >>> resource_fields['address'] = {}
  6. >>> resource_fields['address']['line 1'] = fields.String(attribute='addr1')
  7. >>> resource_fields['address']['line 2'] = fields.String(attribute='addr2')
  8. >>> resource_fields['address']['city'] = fields.String
  9. >>> resource_fields['address']['state'] = fields.String
  10. >>> resource_fields['address']['zip'] = fields.String
  11. >>> data = {'name': 'bob', 'addr1': '123 fake street', 'addr2': '', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  12. >>> json.dumps(marshal(data, resource_fields))
  13. '{"name": "bob", "address": {"line 1": "123 fake street", "line 2": "", "state": "NY", "zip": "10468", "city": "New York"}}'

提示:

地址字段实际上并不存在于数据对象上,但是任何子字段都可以直接从对象访问属性,就好像它们没有嵌套一样。

字段列表

你也可以将字段解组成列表。

  1. >>> from flask_restplus import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> resource_fields = {'name': fields.String, 'first_names': fields.List(fields.String)}
  5. >>> data = {'name': 'Bougnazal', 'first_names' : ['Emile', 'Raoul']}
  6. >>> json.dumps(marshal(data, resource_fields))
  7. >>> '{"first_names": ["Emile", "Raoul"], "name": "Bougnazal"}'

通配符字段

如果你不知道你要解组的字段名称,你可以使用 通配符(Wildcard)

  1. >>> from flask_restplus import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> wild = fields.Wildcard(fields.String)
  5. >>> wildcard_fields = {'*': wild}
  6. >>> data = {'John': 12, 'bob': 42, 'Jane': '68'}
  7. >>> json.dumps(marshal(data, wildcard_fields))
  8. >>> '{"Jane": "68", "bob": "42", "John": "12"}'

通配符 的名称将作为匹配的依据,如下所示

  1. >>> from flask_restplus import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> wild = fields.Wildcard(fields.String)
  5. >>> wildcard_fields = {'j*': wild}
  6. >>> data = {'John': 12, 'bob': 42, 'Jane': '68'}
  7. >>> json.dumps(marshal(data, wildcard_fields))
  8. >>> '{"Jane": "68", "John": "12"}'

提示:

值得注意的是,你需要把 通配符 定义在你的模型外面(也就是说你 不能 这么写:res_fields = {'*': fields.Wildcard(fields.String)}),因为它必须要保存字段是否已经被处理的状态。

提示:

通配符并不是正则表达式,它只能接受通配符‘*’和‘?’。

为了避免意料之外的情况,在混合 通配符 字段和其他字段使用的时候,请使用 有序字典(OrderedDict) 并且将 通配符 字段放在最后面。

  1. >>> from flask_restplus import fields, marshal
  2. >>> from collections import OrderedDict
  3. >>> import json
  4. >>>
  5. >>> wild = fields.Wildcard(fields.Integer)
  6. >>> mod = OrderedDict()
  7. >>> mod['zoro'] = fields.String
  8. >>> mod['*'] = wild
  9. >>> # you can use it in api.model like this:
  10. >>> # some_fields = api.model('MyModel', mod)
  11. >>>
  12. >>> data = {'John': 12, 'bob': 42, 'Jane': '68', 'zoro': 72}
  13. >>> json.dumps(marshal(data, mod))
  14. >>> '{"zoro": "72", "Jane": 68, "bob": 42, "John": 12}'

嵌套字段

虽然你可以通过嵌套字段将平面数据转换成多层结构的响应,但是你也可以通过 Nested 将多层结构的数据转换成适当的形式。

  1. >>> from flask_restplus import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> address_fields = {}
  5. >>> address_fields['line 1'] = fields.String(attribute='addr1')
  6. >>> address_fields['line 2'] = fields.String(attribute='addr2')
  7. >>> address_fields['city'] = fields.String(attribute='city')
  8. >>> address_fields['state'] = fields.String(attribute='state')
  9. >>> address_fields['zip'] = fields.String(attribute='zip')
  10. >>>
  11. >>> resource_fields = {}
  12. >>> resource_fields['name'] = fields.String
  13. >>> resource_fields['billing_address'] = fields.Nested(address_fields)
  14. >>> resource_fields['shipping_address'] = fields.Nested(address_fields)
  15. >>> address1 = {'addr1': '123 fake street', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  16. >>> address2 = {'addr1': '555 nowhere', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  17. >>> data = {'name': 'bob', 'billing_address': address1, 'shipping_address': address2}
  18. >>>
  19. >>> json.dumps(marshal(data, resource_fields))
  20. '{"billing_address": {"line 1": "123 fake street", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}, "name": "bob", "shipping_address": {"line 1": "555 nowhere", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}}'

这个例子使用了两个 嵌套字段(Nested fields)嵌套字段 的构造函数需要一个字段字典作为子字段的输入。一个 嵌套字段(Nested) 构造器和之前嵌套字典(之前的例子)的区别是:属性的上下文。在这个例子中,billing_address 是一个拥有子字段的复杂对象并且传递给嵌套字段的上下文是子对象,而不是原始 data 对象。换句话说: data.billing_address.addr1 作用域在这,而之前例子中 data.addr1 是本地(localtion)属性。请记住:嵌套字段(Nested)列表字段(List) 会为属性创建新的作用域。

在默认情况下,子字段的默认值是 None ,将生成具有嵌套字段的默认值的对象,而不是null。.这可以通过传递 allow_null 参数进行修改,请参阅 嵌套字段(Nested) 构造函数了解更多详细信息。

使用 嵌套字段列表字段 来编组拥有复杂结构的列表对象:

  1. user_fields = api.model('User', {
  2. 'id': fields.Integer,
  3. 'name': fields.String,
  4. })
  5. user_list_fields = api.model('UserList', {
  6. 'users': fields.List(fields.Nested(user_fields)),
  7. })

api.model() 函数(api.model() factory)

model() 函数允许你将你的模型实例化并注册到你的 API 或者 命名空间(Namespace) 中。

  1. my_fields = api.model('MyModel', {
  2. 'name': fields.String,
  3. 'age': fields.Integer(min=0)
  4. })
  5. # Equivalent to
  6. my_fields = Model('MyModel', {
  7. 'name': fields.String,
  8. 'age': fields.Integer(min=0)
  9. })
  10. api.models[my_fields.name] = my_fields

使用 clone进行复制

Model.clone() 函数允许你复制一个已存在的模型,并对其进行扩展。这节省了你复制所有字段的时间。

  1. parent = Model('Parent', {
  2. 'name': fields.String
  3. })
  4. child = parent.clone('Child', {
  5. 'age': fields.Integer
  6. })

Api/Namespace.clone 同时也将其注册到了API中。

  1. parent = api.model('Parent', {
  2. 'name': fields.String
  3. })
  4. child = api.clone('Child', parent, {
  5. 'age': fields.Integer
  6. })

通过api.inherit 实现多态

Model.inherit() 函数允许你通过”Swagger特色的方法(Swagger way)“扩展你的模型并着手于多态的处理。

  1. parent = api.model('Parent', {
  2. 'name': fields.String,
  3. 'class': fields.String(discriminator=True)
  4. })
  5. child = api.inherit('Child', parent, {
  6. 'extra': fields.String
  7. })

Api/Namespace.clone 会同时注册父模型和子模型到Swagger模型定义中。

  1. parent = Model('Parent', {
  2. 'name': fields.String,
  3. 'class': fields.String(discriminator=True)
  4. })
  5. child = parent.inherit('Child', {
  6. 'extra': fields.String
  7. })

只有在序列化对象中不存在属性时,才会使用序列化模型名填充本例中的 class 字段。

Polymorph 字段允许您指定Python类和字段规范(fields specifications)之间的映射。

  1. mapping = {
  2. Child1: child1_fields,
  3. Child2: child2_fields,
  4. }
  5. fields = api.model('Thing', {
  6. owner: fields.Polymorph(mapping)
  7. })

自定义字段

自定义字段使你可以自定义格式化你的输出而不需要修改你的内部对象。你需要做到只是继承父类 Raw 并实现 format() 函数:

  1. class AllCapsString(fields.Raw):
  2. def format(self, value):
  3. return value.upper()
  4. # example usage
  5. fields = {
  6. 'name': fields.String,
  7. 'all_caps_name': AllCapsString(attribute='name'),
  8. }

你可以修改 __ schemaformat\___schematype\___schemaexample\_ 来指定字段输出类型和示例:

  1. class MyIntField(fields.Integer):
  2. __schema_format__ = 'int64'
  3. class MySpecialField(fields.Raw):
  4. __schema_type__ = 'some-type'
  5. __schema_format__ = 'some-format'
  6. class MyVerySpecialField(fields.Raw):
  7. __schema_example__ = 'hello, world'

跳过None字段(Skip fields which value is None)

你可以跳过哪些值为 None 的字段而不是将他们渲染成Json格式的 null 。在你有很多字段值可能为空的时候这是一种很有效降低响应包体积的方法,但是哪个字段是 None 是不可预测的。

让我们看看下面的示例,skip_none 这个关键字被设置为 True

  1. >>> from flask_restplus import Model, fields, marshal_with
  2. >>> import json
  3. >>> model = Model('Model', {
  4. ... 'name': fields.String,
  5. ... 'address_1': fields.String,
  6. ... 'address_2': fields.String
  7. ... })
  8. >>> @marshal_with(model, skip_none=True)
  9. ... def get():
  10. ... return {'name': 'John', 'address_1': None}
  11. ...
  12. >>> get()
  13. OrderedDict([('name', 'John')])

你可以看到 address_1address_2marlshal_with() 跳过了。address_1 被跳过是由于它的值是 Noneaddress_2 被跳过是由于 get() 返回的字典中不含有键 address_2

在嵌套字段中跳过None

如果你的模块中使用了 fields.Nested ,你需要将 skip_none=True 关键字传给 fields.Nested

  1. >>> from flask_restplus import Model, fields, marshal_with
  2. >>> import json
  3. >>> model = Model('Model', {
  4. ... 'name': fields.String,
  5. ... 'location': fields.Nested(location_model, skip_none=True)
  6. ... })

使用Json格式定义模型

你也可以使用 Json格式 (Draft v4)来定义模型。

  1. address = api.schema_model('Address', {
  2. 'properties': {
  3. 'road': {
  4. 'type': 'string'
  5. },
  6. },
  7. 'type': 'object'
  8. })
  9. person = address = api.schema_model('Person', {
  10. 'required': ['address'],
  11. 'properties': {
  12. 'name': {
  13. 'type': 'string'
  14. },
  15. 'age': {
  16. 'type': 'integer'
  17. },
  18. 'birthdate': {
  19. 'type': 'string',
  20. 'format': 'date-time'
  21. },
  22. 'address': {
  23. '$ref': '#/definitions/Address',
  24. }
  25. },
  26. 'type': 'object'
  27. })

请求解析

警告:

Flask-RESTful的整个请求解析器部分将被移除,取而代之的是关于如何与其他更好地完成输入/输出的包(如marshmallow)集成的文档。这意味着它将一直保持到2.0,但是认为它已经过时了。不要担心,如果您的代码现在正在使用它,并且您希望继续这样做,那么它不会很快消失。

基于Flask-RESTful的请求解析接口reqparse是在argparse接口之后建模的。它的设计提供了简单和统一的访问flask.request对象上的任何变量。

基础参数

下面是请求解析器的一个简单示例。它在flask.Request.values字典中查找两个参数:一个整数和一个字符串

  1. from flask_restplus import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('rate', type=int, help='Rate cannot be converted')
  4. parser.add_argument('name')
  5. args = parser.parse_args()

提示:

默认的参数类型是unicode字符串。这在python3中是str,在python2中是unicode。

如果您指定了help值,那么在解析类型错误时,它将被呈现为错误消息。如果没有指定帮助消息,则默认行为是从类型错误本身返回消息。有关详细信息,请参见错误消息

提示:

默认情况下, 不需要 参数。另外,请求中提供的不属于RequestParser的参数将被忽略。

在请求解析器中声明但未在请求本身中设置的参数默认为None。

必要参数

要为参数传递值,只需将required=True添加到add_argument()调用即可。

  1. parser.add_argument('name', required=True, help="Name cannot be blank!")

多个数值和列表

如果您希望一个键能以列表的形式接收多个值,可以像下面这样传递参数action='append'

  1. parser.add_argument('name', action='append')

这会让您的请求变得像下面这样

  1. curl http://api.example.com -d "name=bob" -d "name=sue" -d "name=joe"

并且您的变量看上去会像下面这样

  1. args = parser.parse_args()
  2. args['name'] # ['bob', 'sue', 'joe']

如果您希望用逗号分隔的字符串能被分割成列表,并作为一个键的值,可以像下面这样传递参数action='split'

  1. parser.add_argument('fruits', action='split')

这会让您的请求变得像下面这样

  1. curl http://api.example.com -d "fruits=apple,lemon,cherry"

并且您的变量看上去会像下面这样

  1. args = parser.parse_args()
  2. args['fruits'] # ['apple', 'lemon', 'cherry']

其他源(other destinations)

如果出于某种原因,希望在解析后将参数存储在不同的名称下,那么可以使用dest关键字参数。

  1. parser.add_argument('name', dest='public_name')
  2. args = parser.parse_args()
  3. args['public_name']

参数位置

默认情况下,RequestParser尝试解析来自flask.Request.valuesflask.Request.json的值。

使用add_argument()的location参数来指定从哪些位置获取值。flask.Request上的任何变量都可以使用。例如

  1. # Look only in the POST body
  2. parser.add_argument('name', type=int, location='form')
  3. # Look only in the querystring
  4. parser.add_argument('PageSize', type=int, location='args')
  5. # From the request headers
  6. parser.add_argument('User-Agent', location='headers')
  7. # From http cookies
  8. parser.add_argument('session_id', location='cookies')
  9. # From file uploads
  10. parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

提示:

只有在location=’json’时才使用type=list。有关更多细节,请参见这个issue

使用location=’form’是验证表单数据和记录表单字段的方法。

多位置参数

可以通过将列表传递给location来指定多个参数位置

  1. parser.add_argument('text', location=['headers', 'values'])

当指定多个位置时,来自指定的所有位置的参数将合并为单个MultiDict。最后列出的位置优先于结果集。

如果参数位置列表包含headers,则参数名将不再不区分大小写,必须与标题大小写名称匹配(参见str.title())。指定location='headers'(不作为列表)将保留大小写不敏感。

高级类型处理

有时,您需要比基本数据类型更多的类型来处理输入验证。input模块提供一些常见的类型处理

  • 用于更加广泛布尔处理的 boolean()
  • 用于IP地址的 ipv4()ipv6()
  • 用于ISO8601日期和数据处理的date_from_iso8601()datetime_from_iso8601()

你只需要把它们用在 type 参数上

  1. parser.add_argument('flag', type=inputs.boolean)

有关可用 input 的完整列表,请参阅 input文档

您也可以像下面这样编写自己的数据类型

  1. def my_type(value):
  2. '''Parse my type'''
  3. if not condition:
  4. raise ValueError('This is not my type')
  5. return parse(value)
  6. # Swagger documntation
  7. my_type.__schema__ = {'type': 'string', 'format': 'my-custom-format'}

解析器继承

通常地,您会为您写的每一份资源配置不同的解析器。这样做的问题是解析器是否具有公共的参数。不同于重新写参数,您可以编写一个包含所有公共的参数的父解析器,然后用 copy()函数继承这个解析器。您也可以用 replace_argument()来重写父解析器里的任何参数,或者干脆用 remove_argument() 完全移除它。下面是例子

  1. from flask_restplus import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('foo', type=int)
  4. parser_copy = parser.copy()
  5. parser_copy.add_argument('bar', type=int)
  6. # parser_copy has both 'foo' and 'bar'
  7. parser_copy.replace_argument('foo', required=True, location='json')
  8. # 'foo' is now a required str located in json, not an int as defined
  9. # by original parser
  10. parser_copy.remove_argument('foo')
  11. # parser_copy no longer has 'foo' argument

文件上传

要使用 RequestParser 处理文件上传,您需要使用 files 位置并将 type设置为FileStorage

下面是例子

  1. from werkzeug.datastructures import FileStorage
  2. upload_parser = api.parser()
  3. upload_parser.add_argument('file', location='files',
  4. type=FileStorage, required=True)
  5. @api.route('/upload/')
  6. @api.expect(upload_parser)
  7. class Upload(Resource):
  8. def post(self):
  9. uploaded_file = args['file'] # This is FileStorage instance
  10. url = do_something_with_file(uploaded_file)
  11. return {'url': url}, 201

请参阅专用的Flask文档部分。

错误处理

RequestParser 处理错误的默认方式是在第一个错误出现的时候终止。当您可能需要一些时间来处理某些参数的时候,这将是很有好处的。然而,将错误捆绑一起并且一次性发送回客户端通常是较好的处理。这种方式可以在Flask应用程序级别(Flask application level)或在特定的 RequestParser实例上被指定。为了在调用 RequestParser的时候使用捆绑错误的选项,需要传递 bundle_errors参数。下面是例子

  1. from flask_restplus import reqparse
  2. parser = reqparse.RequestParser(bundle_errors=True)
  3. parser.add_argument('foo', type=int, required=True)
  4. parser.add_argument('bar', type=int, required=True)
  5. # If a request comes in not containing both 'foo' and 'bar', the error that
  6. # will come back will look something like this.
  7. {
  8. "message": {
  9. "foo": "foo error message",
  10. "bar": "bar error message"
  11. }
  12. }
  13. # The default behavior would only return the first error
  14. parser = RequestParser()
  15. parser.add_argument('foo', type=int, required=True)
  16. parser.add_argument('bar', type=int, required=True)
  17. {
  18. "message": {
  19. "foo": "foo error message"
  20. }
  21. }

程序的配置键是 “BUNDLE_ERRORS”,下面是例子

  1. from flask import Flask
  2. app = Flask(__name__)
  3. app.config['BUNDLE_ERRORS'] = True

警告:

BUNDLE_ERRORS 是一个重载了每个 RequestParser 实例里的 bundle_errors 选项的全局设定

错误消息

每个域的错误消息可以通过 help 参数来进行定制(也是在 RequestParser.add_argument当中)。

如果不提供 help 参数,那么这个域的错误消息会是错误类型本身的字符串表示。否则,错误消息就是 help 参数的值

help 参数可能包含一个插值标记( interpolation token),就像 {error_msg} 这样,这个标记将会被错误类型的字符串表示替换。这允许您在保留原本的错误消息的同时定制消息,就像下面的例子这样

  1. from flask_restplus import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument(
  4. 'foo',
  5. choices=('one', 'two'),
  6. help='Bad choice: {error_msg}'
  7. )
  8. # If a request comes in with a value of "three" for `foo`:
  9. {
  10. "message": {
  11. "foo": "Bad choice: three is not a valid choice",
  12. }
  13. }

字段掩码(Fields masks)

Flask-RESTPlus通过一个自定义请求头支持部分对象获取(partial object fetching)也就是字段掩码(fields mask)。

默认情况下头名为 X-Fields ,但是它可以被 RESTPLUS_MASK_HEADER 参数修改。

语法

语法非常简单。你只要提供一个包含字段名并用逗号分隔的列表,可以选择性的用括号包裹。

  1. # These two mask are equivalents
  2. mask = '{name,age}'
  3. # or
  4. mask = 'name,age'
  5. data = requests.get('/some/url/', headers={'X-Fields': mask})
  6. assert len(data) == 2
  7. assert 'name' in data
  8. assert 'age' in data

实现嵌套字段只需要将内容用大括号包裹即可。

  1. mask = '{name, age, pet{name}}'

嵌套规范适用于嵌套对象或对象列表:

  1. # Will apply the mask {name} to each pet
  2. # in the pets list.
  3. mask = '{name, age, pets{name}}'

特殊字符米字星(*)代表“所有剩余字段(all remaining fields)”。它仅允许指定嵌套过滤:

  1. # Will apply the mask {name} to each pet
  2. # in the pets list and take all other root fields
  3. # without filtering.
  4. mask = '{pets{name},*}'
  5. # Will not filter anything
  6. mask = '*'

使用方法

默认情况下,每次使用 api.marshal@api.marshal_with 时,如果存在标头,掩码将自动应用。

当你每次使用 @api.marshal_with 修饰器时,标头将作为Swagger参数展示。

由于Swagger并不允许展示全局标头,这将会使你的Swagger文档更加冗长。你可以修改 RESTPLUS_MASK_SWAGGERFalse 来禁用这个功能。

您也可以指定默认的掩码,如果找不到掩码,则将应用默认掩码。

  1. class MyResource(Resource):
  2. @api.marshal_with(my_model, mask='name,age')
  3. def get(self):
  4. pass

默认掩码也可以在模型级别处理:

  1. model = api.model('Person', {
  2. 'name': fields.String,
  3. 'age': fields.Integer,
  4. 'boolean': fields.Boolean,
  5. }, mask='{name,age}')

它将被导出到 x-mask 字段:

  1. {"definitions": {
  2. "Test": {
  3. "properties": {
  4. "age": {"type": "integer"},
  5. "boolean": {"type": "boolean"},
  6. "name": {"type": "string"}
  7. },
  8. "x-mask": "{name,age}"
  9. }
  10. }}

要覆盖默认掩码,您需要提供另一个掩码或将*用作掩码。

Swagger文档

Swagger API文档是自动生成的,可从您API的根目录访问。你可以使用 @api.doc() 修饰器配置你的文档。

使用@api.doc()装饰器进行文档编辑

@api.doc() 修饰器使你可以为文档添加额外信息。

你可以为一个类或者函数添加文档:

  1. @api.route('/my-resource/<id>', endpoint='my-resource')
  2. @api.doc(params={'id': 'An ID'})
  3. class MyResource(Resource):
  4. def get(self, id):
  5. return {}
  6. @api.doc(responses={403: 'Not Authorized'})
  7. def post(self, id):
  8. api.abort(403)

模型自动记录

所有由 model()clone()inherit() 实例化的模型(model)都会被自动记录到Swagger文档中。

inherit() 函数会将父类和子类都注册到Swagger的模型(model)定义中:

  1. parent = api.model('Parent', {
  2. 'name': fields.String,
  3. 'class': fields.String(discriminator=True)
  4. })
  5. child = api.inherit('Child', parent, {
  6. 'extra': fields.String
  7. })

上面的代码会生成下面的Swagger定义:

  1. {
  2. "Parent": {
  3. "properties": {
  4. "name": {"type": "string"},
  5. "class": {"type": "string"}
  6. },
  7. "discriminator": "class",
  8. "required": ["class"]
  9. },
  10. "Child": {
  11. "allOf": [
  12. {
  13. "$ref": "#/definitions/Parent"
  14. }, {
  15. "properties": {
  16. "extra": {"type": "string"}
  17. }
  18. }
  19. ]
  20. }
  21. }

@api.marshal_with()装饰器

这个装饰器和原生的 marshal_with() 装饰器几乎完全一致,除了这个装饰器会记录函数文档。可选参数代码允许您指定期望的HTTP状态码(默认为200)。可选参数 as_list 允许您指定是否将对象作为列表返回。

  1. resource_fields = api.model('Resource', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/<id>', endpoint='my-resource')
  5. class MyResource(Resource):
  6. @api.marshal_with(resource_fields, as_list=True)
  7. def get(self):
  8. return get_objects()
  9. @api.marshal_with(resource_fields, code=201)
  10. def post(self):
  11. return create_object(), 201

Api.marshal_list_with() 装饰器严格等同于 Api.marshal_with(fields,** **as_list=True)()

  1. resource_fields = api.model('Resource', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/<id>', endpoint='my-resource')
  5. class MyResource(Resource):
  6. @api.marshal_list_with(resource_fields)
  7. def get(self):
  8. return get_objects()
  9. @api.marshal_with(resource_fields)
  10. def post(self):
  11. return create_object()

@api.expect()装饰器

@api.expect() 装饰器允许你指定所需的输入字段。它接受一个可选的布尔参数 validate ,指示负载(payload)是否需要被验证。

可以通过将 RESTPLUS_VALIDATE 配置设置为 True 或将 validate = True 传递给API构造函数来全局设置验证功能。

以下示例是等效的:

  • 使用 @api.expect()装饰器:

    1. resource_fields = api.model('Resource', {
    2. 'name': fields.String,
    3. })
    4. @api.route('/my-resource/<id>')
    5. class MyResource(Resource):
    6. @api.expect(resource_fields)
    7. def get(self):
    8. pass
  • 使用 @api.doc() 装饰器:

    1. resource_fields = api.model('Resource', {
    2. 'name': fields.String,
    3. })
    4. @api.route('/my-resource/<id>')
    5. class MyResource(Resource):
    6. @api.doc(body=resource_fields)
    7. def get(self):
    8. pass

您可以将列表指定为预期输入:

  1. resource_fields = api.model('Resource', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/<id>')
  5. class MyResource(Resource):
  6. @api.expect([resource_fields])
  7. def get(self):
  8. pass

您可以使用 RequestParser 定义期望的输入:

  1. parser = api.parser()
  2. parser.add_argument('param', type=int, help='Some param', location='form')
  3. parser.add_argument('in_files', type=FileStorage, location='files')
  4. @api.route('/with-parser/', endpoint='with-parser')
  5. class WithParserResource(restplus.Resource):
  6. @api.expect(parser)
  7. def get(self):
  8. return {}

可以在特定端点上启用或禁用验证:

  1. resource_fields = api.model('Resource', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/<id>')
  5. class MyResource(Resource):
  6. # Payload validation disabled
  7. @api.expect(resource_fields)
  8. def post(self):
  9. pass
  10. # Payload validation enabled
  11. @api.expect(resource_fields, validate=True)
  12. def post(self):
  13. pass

通过config进行应用程序范围验证设置的示例:

  1. app.config['RESTPLUS_VALIDATE'] = True
  2. api = Api(app)
  3. resource_fields = api.model('Resource', {
  4. 'name': fields.String,
  5. })
  6. @api.route('/my-resource/<id>')
  7. class MyResource(Resource):
  8. # Payload validation enabled
  9. @api.expect(resource_fields)
  10. def post(self):
  11. pass
  12. # Payload validation disabled
  13. @api.expect(resource_fields, validate=False)
  14. def post(self):
  15. pass

通过构造函数进行应用程序范围验证设置的示例:

  1. api = Api(app, validate=True)
  2. resource_fields = api.model('Resource', {
  3. 'name': fields.String,
  4. })
  5. @api.route('/my-resource/<id>')
  6. class MyResource(Resource):
  7. # Payload validation enabled
  8. @api.expect(resource_fields)
  9. def post(self):
  10. pass
  11. # Payload validation disabled
  12. @api.expect(resource_fields, validate=False)
  13. def post(self):
  14. pass

使用@api.response装饰器进行文档编辑

@api.response 装饰器允许您记录已知的响应,并且他是 @api.doc(responses='...') 的简化写法。

以下两种定义是等效的:

  1. @api.route('/my-resource/')
  2. class MyResource(Resource):
  3. @api.response(200, 'Success')
  4. @api.response(400, 'Validation Error')
  5. def get(self):
  6. pass
  7. @api.route('/my-resource/')
  8. class MyResource(Resource):
  9. @api.doc(responses={
  10. 200: 'Success',
  11. 400: 'Validation Error'
  12. })
  13. def get(self):
  14. pass

您可以选择将响应模型指定为第三个参数:

  1. model = api.model('Model', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/')
  5. class MyResource(Resource):
  6. @api.response(200, 'Success', model)
  7. def get(self):
  8. pass

@api.marshal_with() 修饰器会自动记录响应:

  1. model = api.model('Model', {
  2. 'name': fields.String,
  3. })
  4. @api.route('/my-resource/')
  5. class MyResource(Resource):
  6. @api.response(400, 'Validation error')
  7. @api.marshal_with(model, code=201, description='Object created')
  8. def post(self):
  9. pass

如果你不知道状态码的时候,你可以指定一个默认响应。

  1. @api.route('/my-resource/')
  2. class MyResource(Resource):
  3. @api.response('default', 'Error')
  4. def get(self):
  5. pass

@api.route()装饰器

你可以指定一个类范围的文档通过 Api.route()doc 参数。这个参数可以接受和 @api.doc() 装饰器相同的参数。

例如,这两种定义是等效的:

  • 使用 @api.doc():

    1. @api.route('/my-resource/<id>', endpoint='my-resource')
    2. @api.doc(params={'id': 'An ID'})
    3. class MyResource(Resource):
    4. def get(self, id):
    5. return {}
  • 使用 @api.route():

    1. @api.route('/my-resource/<id>', endpoint='my-resource', doc={'params':{'id': 'An ID'}})
    2. class MyResource(Resource):
    3. def get(self, id):
    4. return {}

单资源类多路由(Multiple Routes per Resource)

多个 Api.route() 修饰器可以为单个 资源类(Resource) 添加多个路由。 doc 参数可以为每条路由配置文档。

例如,下面的 描述(description) 只适用于路由 /also-my-resource/<id>

  1. @api.route("/my-resource/<id>")
  2. @api.route(
  3. "/also-my-resource/<id>",
  4. doc={"description": "Alias for /my-resource/<id>"},
  5. )
  6. class MyResource(Resource):
  7. def get(self, id):
  8. return {}

这里,路由 /also-my-resource/<id> 则标记为已弃用:

  1. @api.route("/my-resource/<id>")
  2. @api.route(
  3. "/also-my-resource/<id>",
  4. doc={
  5. "description": "Alias for /my-resource/<id>, this route is being phased out in V2",
  6. "deprecated": True,
  7. },
  8. )
  9. class MyResource(Resource):
  10. def get(self, id):
  11. return {}

除非明确覆盖,否则由 Api.doc()资源类(Resource) 绑定的文档将在各路由间共享:

  1. @api.route("/my-resource/<id>")
  2. @api.route(
  3. "/also-my-resource/<id>",
  4. doc={"description": "Alias for /my-resource/<id>"},
  5. )
  6. @api.doc(params={"id": "An ID", description="My resource"})
  7. class MyResource(Resource):
  8. def get(self, id):
  9. return {}

这里, 来自 Api.doc()id 文档同时存在于两条路由上, /my-resource/<id> 继承了 My resourceApi.doc() 记录的描述,而 /also-my-resource/<id>Alias for /my-resource/<id> 覆盖了描述。

doc 标记的路由将获得一个 唯一 的Swagger operationId 。没有 doc 参数的路由将拥有相同的 operationId ,它们会被视为相同的操作。

对字段进行文档编写

每个Flask-RESTPlus字段都可以可选的接受以下几个用于文档的参数:

  • required :一个布朗值标识这个字段是否是必要的(默认:False
  • description:一些字段的详细描述(默认:None
  • example :展示时显示的示例(默认: None

这里还有一些特定字段的属性:

  • String 字段可以接受以下参数:
    • enum :一个限制授权值的数组。
    • min_length :字符串的最小长度。
    • max_length :字符串的最大长度。
    • pattern :一个正则表达式用于验证。
  • IntegerFloatArbitrary 字段可以接受以下参数:
    • min :可以接受的最小值。
    • max :可以接受的最大值。
    • ExclusiveMin :如果为 True ,则区间不包含最小值。
    • exclusiveMax :如果为 True ,则区间不包含最大值。
    • multiple :限制输入的数字是这个数的倍数。
  • DateTime 字段可以接受 minmaxexclusiveMinexclusiveMax 参数。这些参数必须是 datesdatetimes (不是ISO字符串就是原生对象)。
  1. my_fields = api.model('MyModel', {
  2. 'name': fields.String(description='The name', required=True),
  3. 'type': fields.String(description='The object type', enum=['A', 'B']),
  4. 'age': fields.Integer(min=0),
  5. })

对函数进行文档编写

每一个资源类都会被记录为一个Swagger路径。

每一个资源类的函数(get , post, put , delete , path , options , head)都会被记录为一个Swagger操作。

您可以使用 id 关键字参数指定唯一的Swagger operationId

  1. @api.route('/my-resource/')
  2. class MyResource(Resource):
  3. @api.doc(id='get_something')
  4. def get(self):
  5. return {}

设置第一个参数也可以达到相同的目的:

  1. @api.route('/my-resource/')
  2. class MyResource(Resource):
  3. @api.doc('get_something')
  4. def get(self):
  5. return {}

如果没有特别指定,默认将以下面的格式设定 operationId

  1. {{verb}}_{{resource class name | camelCase2dashes }}

前面的例子中,默认的 operationId 将会是 get_my_resource

你可以通过给 default_id 传入一个回调函数来覆盖默认的 operationId 生成器。这个回调函数接受下面两个参数:

  • 资源类的类名
  • 小写的HTTP方法
  1. def default_id(resource, method):
  2. return ''.join((method, resource))
  3. api = Api(app, default_id=default_id)

前面的例子中,生成的 operationId 将会是 getMyResource

每个操作都会自动纳入其命名空间的标签下。如果资源类是直接归属于根目录,则自动纳入默认标签中。

函数参数

来自url地址的参数会自动被记录。你可以通过 api.doc() 修饰器的 params 参数添加额外的内容:

  1. @api.route('/my-resource/<id>', endpoint='my-resource')
  2. @api.doc(params={'id': 'An ID'})
  3. class MyResource(Resource):
  4. pass

或者使用 api.params 修饰器:

  1. @api.route('/my-resource/<id>', endpoint='my-resource')
  2. @api.param('id', 'An ID')
  3. class MyResource(Resource):
  4. pass

输入和输出模型

你可以通过 api.doc() 修饰器的 model 关键字指定序列化输出模型。

对于 PUTPOST 方法,使用 body 关键字指定输入模型。

  1. fields = api.model('MyModel', {
  2. 'name': fields.String(description='The name', required=True),
  3. 'type': fields.String(description='The object type', enum=['A', 'B']),
  4. 'age': fields.Integer(min=0),
  5. })
  6. @api.model(fields={'name': fields.String, 'age': fields.Integer})
  7. class Person(fields.Raw):
  8. def format(self, value):
  9. return {'name': value.name, 'age': value.age}
  10. @api.route('/my-resource/<id>', endpoint='my-resource')
  11. @api.doc(params={'id': 'An ID'})
  12. class MyResource(Resource):
  13. @api.doc(model=fields)
  14. def get(self, id):
  15. return {}
  16. @api.doc(model='MyModel', body=Person)
  17. def post(self, id):
  18. return {}

如果 bodyformData 同时使用,将会造成 SpecsError 异常。

模型同时也可以被 RequestParser 指定。

  1. parser = api.parser()
  2. parser.add_argument('param', type=int, help='Some param', location='form')
  3. parser.add_argument('in_files', type=FileStorage, location='files')
  4. @api.route('/with-parser/', endpoint='with-parser')
  5. class WithParserResource(restplus.Resource):
  6. @api.expect(parser)
  7. def get(self):
  8. return {}

提示:

解码后的有效载荷(decoded payload)将以字典的形式作为 有效载荷(payload)的属性存在在请求上下文中(request context)。

  1. @api.route('/my-resource/')
  2. class MyResource(Resource):
  3. def get(self):
  4. data = api.payload

提示:

更推荐使用 RequestParser 而不是 api.param() 修饰器对表单进行记录,因为前者同时支持表单验证。

头(headers)

你可以使用 api.header() 修饰器快捷记录响应头内容。

  1. @api.route('/with-headers/')
  2. @api.header('X-Header', 'Some class header')
  3. class WithHeaderResource(restplus.Resource):
  4. @api.header('X-Collection', type=[str], collectionType='csv')
  5. def get(self):
  6. pass

如果你要指定一个只出现在响应中的标头,只需要使用 @api.responseheaders 关键字即可。

  1. @api.route('/response-headers/')
  2. class WithHeaderResource(restplus.Resource):
  3. @api.response(200, 'Success', headers={'X-Header': 'Some header'})
  4. def get(self):
  5. pass

记录 期望或者需求(expected/request) 的标头请使用 @api.expect 修饰符。

  1. parser = api.parser()
  2. parser.add_argument('Some-Header', location='headers')
  3. @api.route('/expect-headers/')
  4. @api.expect(parser)
  5. class ExpectHeaderResource(restplus.Resource):
  6. def get(self):
  7. pass

级联(Cascading)

函数的文档优先级高于类的文档,继承的文档高于其父类的文档。

例如,这两个声明是等效的:

  • 函数文档继承类文档内容:

    1. @api.route('/my-resource/<id>', endpoint='my-resource')
    2. @api.params('id', 'An ID')
    3. class MyResource(Resource):
    4. def get(self, id):
    5. return {}
  • 函数文档覆盖类文档内容:

    1. @api.route('/my-resource/<id>', endpoint='my-resource')
    2. @api.param('id', 'Class-wide description')
    3. class MyResource(Resource):
    4. @api.param('id', 'An ID')
    5. def get(self, id):
    6. return {}

你也可以用类装饰器指定函数的文档。以下示例将产生与前两个示例相同的文档:

  1. @api.route('/my-resource/<id>', endpoint='my-resource')
  2. @api.params('id', 'Class-wide description')
  3. @api.doc(get={'params': {'id': 'An ID'}})
  4. class MyResource(Resource):
  5. def get(self, id):
  6. return {}

已弃用标记

你可以通过 @api.deprecated 修饰器将资源类或函数标记为已弃用:

  1. # Deprecate the full resource
  2. @api.deprecated
  3. @api.route('/resource1/')
  4. class Resource1(Resource):
  5. def get(self):
  6. return {}
  7. # Deprecate methods
  8. @api.route('/resource4/')
  9. class Resource4(Resource):
  10. def get(self):
  11. return {}
  12. @api.deprecated
  13. def post(self):
  14. return {}
  15. def put(self):
  16. return {}

隐藏文档

用下面的方法你可以将一些资源类或函数从文档种隐藏:

  1. # Hide the full resource
  2. @api.route('/resource1/', doc=False)
  3. class Resource1(Resource):
  4. def get(self):
  5. return {}
  6. @api.route('/resource2/')
  7. @api.doc(False)
  8. class Resource2(Resource):
  9. def get(self):
  10. return {}
  11. @api.route('/resource3/')
  12. @api.hide
  13. class Resource3(Resource):
  14. def get(self):
  15. return {}
  16. # Hide methods
  17. @api.route('/resource4/')
  18. @api.doc(delete=False)
  19. class Resource4(Resource):
  20. def get(self):
  21. return {}
  22. @api.doc(False)
  23. def post(self):
  24. return {}
  25. @api.hide
  26. def put(self):
  27. return {}
  28. def delete(self):
  29. return {}

提示:

没有附加的资源类的命名空间会自动的在文档中隐藏。

文档授权(Documenting authorizations)

你可以通过 authorizations 关键字修改文档授权信息。查看 Swagger授权文档(Swagger Authentication documentation) 了解详细配置方法。

  • authorizations 是以Python字典的形式表现Swagger securityDefinitions 的配置信息。

    1. authorizations = {
    2. 'apikey': {
    3. 'type': 'apiKey',
    4. 'in': 'header',
    5. 'name': 'X-API-KEY'
    6. }
    7. }
    8. api = Api(app, authorizations=authorizations)

配置授权之后每个资源类和方法的解释器均需配置授权:

  1. @api.route('/resource/')
  2. class Resource1(Resource):
  3. @api.doc(security='apikey')
  4. def get(self):
  5. pass
  6. @api.doc(security='apikey')
  7. def post(self):
  8. pass

你可以通过 security 关键字在 Api 的构造函数中全局的应用这个配置:

  1. authorizations = {
  2. 'apikey': {
  3. 'type': 'apiKey',
  4. 'in': 'header',
  5. 'name': 'X-API-KEY'
  6. }
  7. }
  8. api = Api(app, authorizations=authorizations, security='apikey')

你也可以设置多种授权机制:

  1. authorizations = {
  2. 'apikey': {
  3. 'type': 'apiKey',
  4. 'in': 'header',
  5. 'name': 'X-API'
  6. },
  7. 'oauth2': {
  8. 'type': 'oauth2',
  9. 'flow': 'accessCode',
  10. 'tokenUrl': 'https://somewhere.com/token',
  11. 'authorizationUrl': 'https://somewhere.com/auth',
  12. 'scopes': {
  13. 'read': 'Grant read-only access',
  14. 'write': 'Grant read-write access',
  15. }
  16. }
  17. }
  18. api = Api(self.app, security=['apikey', {'oauth2': 'read'}], authorizations=authorizations)

安全机制也可以通过特定的函数覆盖:

  1. @api.route('/authorizations/')
  2. class Authorized(Resource):
  3. @api.doc(security=[{'oauth2': ['read', 'write']}])
  4. def get(self):
  5. return {}

你可以通过给 security 关键字传入 None 或一个空列表禁用某个资源类或方法的安全机制:

  1. @api.route('/without-authorization/')
  2. class WithoutAuthorization(Resource):
  3. @api.doc(security=[])
  4. def get(self):
  5. return {}
  6. @api.doc(security=None)
  7. def post(self):
  8. return {}

展示支持信息(Expose vendor Extensions)

Swagger允许你自定义 支持信息(vendor extensions ) ,而Flask-RESTPlus可以通过 @api.vendor 修饰器对其进行设置。

它同时支持 dictkwargs 扩展,并自动执行 x-prefix

  1. @api.route('/vendor/')
  2. @api.vendor(extension1='any authorized value')
  3. class Vendor(Resource):
  4. @api.vendor({
  5. 'extension-1': {'works': 'with complex values'},
  6. 'x-extension-3': 'x- prefix is optionnal',
  7. })
  8. def get(self):
  9. return {}

导出Swagger格式

你可以将你的API导出为Swagger格式:

  1. from flask import json
  2. from myapp import api
  3. print(json.dumps(api.__schema__))

Swagger UI

在默认情况下,Flask-RESTPlus 在API的根目录提供 Swagger UI 文档服务。

  1. from flask import Flask
  2. from flask_restplus import Api, Resource, fields
  3. app = Flask(__name__)
  4. api = Api(app, version='1.0', title='Sample API',
  5. description='A sample API',
  6. )
  7. @api.route('/my-resource/<id>')
  8. @api.doc(params={'id': 'An ID'})
  9. class MyResource(Resource):
  10. def get(self, id):
  11. return {}
  12. @api.response(403, 'Not Authorized')
  13. def post(self, id):
  14. api.abort(403)
  15. if __name__ == '__main__':
  16. app.run(debug=True)

运行上面的代码并访问API的根目录(http://localhost:5000),你就能看到自动生成的Swagger UI文档。

Flask-RESTPlus 中文文档(Flask-RESTPlus Chinese document) - 图1

个性化

你可以通过 doc 关键字配置 Swagger UI 的路径(默认为根目录):

  1. from flask import Flask, Blueprint
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. blueprint = Blueprint('api', __name__, url_prefix='/api')
  5. api = Api(blueprint, doc='/doc/')
  6. app.register_blueprint(blueprint)
  7. assert url_for('api.doc') == '/api/doc/'

你可以通过设定 config.SWAGGER_VALIDATOR_URL 来指定一个自定义的验证器地址(validator URL):

  1. from flask import Flask
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. app.config.SWAGGER_VALIDATOR_URL = 'http://domain.com/validator'
  5. api = Api(app)

您可以启用 OAuth2隐式流程(OAuth2 Implicit Flow) ,以获取用于在Swagger UI中交互测试api端点的授权令牌。 config.SWAGGER_UI_OAUTH_CLIENT_IDauthorizationUrlscopes 将用于指定你的OAuth2 IDP配置。 域字符串(realm string) 将会作为查询参数(query parameter) 添加到 授权地址(authorizationUrl) 和 凭证地址(tokenUrl)。这些值都是公开信息。此处未指定 客户端密钥(client secret)。使用PKCE代替隐式流取决于https://github.com/swagger-api/swagger-ui/issues/5348

  1. from flask import Flask
  2. app = Flask(__name__)
  3. app.config.SWAGGER_UI_OAUTH_CLIENT_ID = 'MyClientId'
  4. app.config.SWAGGER_UI_OAUTH_REALM = '-'
  5. app.config.SWAGGER_UI_OAUTH_APP_NAME = 'Demo'
  6. api = Api(
  7. app,
  8. title=app.config.SWAGGER_UI_OAUTH_APP_NAME,
  9. security={'OAuth2': ['read', 'write']},
  10. authorizations={
  11. 'OAuth2': {
  12. 'type': 'oauth2',
  13. 'flow': 'implicit',
  14. 'authorizationUrl': 'https://idp.example.com/authorize?audience=https://app.example.com',
  15. 'clientId': app.config.SWAGGER_UI_OAUTH_CLIENT_ID,
  16. 'scopes': {
  17. 'openid': 'Get ID token',
  18. 'profile': 'Get identity',
  19. }
  20. }
  21. }
  22. )

你也可以通过修改 config.SWAGGER_UI_DOC_EXPANSION ('none', 'list''full') 来指定初期标签展开状态(the initial expansion state)。

  1. from flask_restplus import Api
  2. app = Flask(__name__)
  3. app.config.SWAGGER_UI_DOC_EXPANSION = 'list'
  4. api = Api(app)

默认情况下, 操作ID(operation ID)请求区间(request duration) 是影藏的,可以通过下面的方法分别启用它们:

  1. from flask import Flask
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. app.config.SWAGGER_UI_OPERATION_ID = True
  5. app.config.SWAGGER_UI_REQUEST_DURATION = True
  6. api = Api(app)

如果你需要自定义UI,你可以通过 documentation() 修饰器来注册自定义视图:

  1. from flask import Flask
  2. from flask_restplus import Api, apidoc
  3. app = Flask(__name__)
  4. api = Api(app)
  5. @api.documentation
  6. def custom_ui():
  7. return apidoc.ui_for(api)

配置“试一试(Try it Out)”

默认情况下,所有的路径和方法都有一个“试一试(Try it Out)”按钮用于在浏览器中测试API。你可以通过修改 SWAGGER_SUPPORTED_SUBMIT_METHODS 的配置禁用任意一种Http方法,该参数支持符合 Swagger UI 参数(Swagger UI parameter)supportedSubmitMethods 参数的所有值。

  1. from flask import Flask
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. # disable Try it Out for all methods
  5. app.config.SWAGGER_SUPPORTED_SUBMIT_METHODS = []
  6. # enable Try it Out for specific methods
  7. app.config.SWAGGER_SUPPORTED_SUBMIT_METHODS = ["get", "post"]
  8. api = Api(app)

禁用文档

设置 doc=False 可以完全禁用文档。

  1. from flask import Flask
  2. from flask_restplus import Api
  3. app = Flask(__name__)
  4. api = Api(app, doc=False)

异常处理

Http异常处理

Werkzeug HTTP异常(Werkzeug HTTPException)将适当的自动重写描述(description)属性。

  1. from werkzeug.exceptions import BadRequest
  2. raise BadRequest()

上述代码将会返回一个400状态码和输出:

  1. {
  2. "message": "The browser (or proxy) sent a request that this server could not understand."
  3. }

而这段代码:

  1. from werkzeug.exceptions import BadRequest
  2. raise BadRequest('My custom message')

将会输出:

  1. {
  2. "message": "My custom message"
  3. }

你可以通过修改data属性值添加额外的参数到你的异常中:

  1. from werkzeug.exceptions import BadRequest
  2. e = BadRequest('My custom message')
  3. e.data = {'custom': 'value'}
  4. raise e

这将输出:

  1. {
  2. "message": "My custom message",
  3. "custom": "value"
  4. }

Flask终止助手

终止助手(abort helper) 适当的将错误封装成了一个 Http异常( HTTPException ) ,因此它们表现几乎相同。

  1. from flask import abort
  2. abort(400)

上述代码将会返回一个400状态码和输出:

  1. {
  2. "message": "The browser (or proxy) sent a request that this server could not understand."
  3. }

而这段代码:

  1. from flask import abort
  2. abort(400, 'My custom message')

将会输出:

  1. {
  2. "message": "My custom message"
  3. }

Flask-RESTPlus终止助手

errors.abort()Namespace.abort() 终止助手与原生Flask Flask.abort() 原理相似,但将会把关键字参数(keyword arguments)打包进响应中。

  1. from flask_restplus import abort
  2. abort(400, custom='value')

上述代码将会返回一个400状态码和输出:

  1. {
  2. "message": "The browser (or proxy) sent a request that this server could not understand.",
  3. "custom": "value"
  4. }

而这段代码:

  1. from flask import abort
  2. abort(400, 'My custom message', custom='value')

将会输出:

  1. {
  2. "message": "My custom message",
  3. "custom": "value"
  4. }

@api.errorhandler 装饰器

@api.errorhandler装饰器将为指定的异常(或继承于这个异常的任何异常)注册一个特别的处理机(handler),你也可以用同样的方法使用 Flask/Blueprint 的 @errorhandler装饰器。

  1. @api.errorhandler(RootException)
  2. def handle_root_exception(error):
  3. '''Return a custom message and 400 status code'''
  4. return {'message': 'What you want'}, 400
  5. @api.errorhandler(CustomException)
  6. def handle_custom_exception(error):
  7. '''Return a custom message and 400 status code'''
  8. return {'message': 'What you want'}, 400
  9. @api.errorhandler(AnotherException)
  10. def handle_another_exception(error):
  11. '''Return a custom message and 500 status code'''
  12. return {'message': error.specific}
  13. @api.errorhandler(FakeException)
  14. def handle_fake_exception_with_header(error):
  15. '''Return a custom message and 400 status code'''
  16. return {'message': error.message}, 400, {'My-Header': 'Value'}
  17. @api.errorhandler(NoResultFound)
  18. def handle_no_result_exception(error):
  19. '''Return a custom not found error message and 404 status code'''
  20. return {'message': error.specific}, 404

提示:

一个带有描述的“未找到结果(NoResultFound)”异常是 OpenAPI 2.0规范所规定的。处理机种的文档字符串(docstring)(译者:就是那坨三引号)将会被输出到swagger.json中作为描述。

你也可以专门为异常编写文档:

  1. @api.errorhandler(FakeException)
  2. @api.marshal_with(error_fields, code=400)
  3. @api.header('My-Header', 'Some description')
  4. def handle_fake_exception_with_header(error):
  5. '''This is a custom error'''
  6. return {'message': error.message}, 400, {'My-Header': 'Value'}
  7. @api.route('/test/')
  8. class TestResource(Resource):
  9. def get(self):
  10. '''
  11. Do something
  12. :raises CustomException: In case of something
  13. '''
  14. pass

在这个例子里,:raises:字符串将会被自动提取并填充至文档400错误处。

你只需要在使用时忽略参数,就可以重写默认的 errorhandler

  1. @api.errorhandler
  2. def default_error_handler(error):
  3. '''Default error handler'''
  4. return {'message': str(error)}, getattr(error, 'code', 500)

提示:

Flask-RESTPlus 默认会返回一个带消息的错误信息。如果你在自定义一个错误响应并且不需要消息字段的话,你可以在配置文件中将 ERROR_INCLUDE_MESSAGE 改为 False 以禁用消息字段。

errorhandler也可以在命名空间中注册。在命名空间中注册的处理机将会覆盖在 Api 中注册的处理机。

  1. ns = Namespace('cats', description='Cats related operations')
  2. @ns.errorhandler
  3. def specific_namespace_error_handler(error):
  4. '''Namespace error handler'''
  5. return {'message': str(error)}, getattr(error, 'code', 500)

Postman

为了方便你测试,你可以将你的API导出为一个 Postman 集合(Postman collection)。

  1. from flask import json
  2. from myapp import api
  3. urlvars = False # Build query strings in URLs
  4. swagger = True # Export Swagger specifications
  5. data = api.as_postman(urlvars=urlvars, swagger=swagger)
  6. print(json.dumps(data))

项目扩展

本章涵盖构建稍微复杂一些的Flask-RESTPlus应用程序,该程序将为在实际部署一个基于Flask-RESTPlus的应用程序前提供一些最佳的实践。快速开始 章节更加适合第一次接触Flask-RESTPlus的人,所以如果你是Flask-RESTPlus的初学者请先查看快速开始章节。

多命名空间

这里有很多种方法组织你的Flask-RESTPlus应用程序代码,而下面我们将介绍一种在大型应用程序种保持良好的组织性和优秀的可扩展性的一种方法。

Flask-RESTPlus 提供了一种几乎与 Flask蓝图(Flask’s blueprint)相同的功能。它的主要思路是将应用程序分割为多个可重用的 命名空间(Namespace)。

下面是一个目录结构的例子:

  1. project/
  2. ├── app.py
  3. ├── core
  4. ├── __init__.py
  5. ├── utils.py
  6. └── ...
  7. └── apis
  8. ├── __init__.py
  9. ├── namespace1.py
  10. ├── namespace2.py
  11. ├── ...
  12. └── namespaceX.py

app 模块将作为一个遵循经典的Flask模式之一(详见 Larger Applications and Application Factories)的主程序入口(entry point)。

core 模块包含了事务逻辑。实际上你爱叫啥叫啥,甚至可以是很多个包。

apis 模块将作为你的API的主入口,你需要在这里导入并注册你的应用程序,而命名空间模块就按照你平时写Flask蓝图的时候写就行。

一个命名空间的模块要包含模型和资源类的声明。举个例子:

  1. from flask_restplus import Namespace, Resource, fields
  2. api = Namespace('cats', description='Cats related operations')
  3. cat = api.model('Cat', {
  4. 'id': fields.String(required=True, description='The cat identifier'),
  5. 'name': fields.String(required=True, description='The cat name'),
  6. })
  7. CATS = [
  8. {'id': 'felix', 'name': 'Felix'},
  9. ]
  10. @api.route('/')
  11. class CatList(Resource):
  12. @api.doc('list_cats')
  13. @api.marshal_list_with(cat)
  14. def get(self):
  15. '''List all cats'''
  16. return CATS
  17. @api.route('/<id>')
  18. @api.param('id', 'The cat identifier')
  19. @api.response(404, 'Cat not found')
  20. class Cat(Resource):
  21. @api.doc('get_cat')
  22. @api.marshal_with(cat)
  23. def get(self, id):
  24. '''Fetch a cat given its identifier'''
  25. for cat in CATS:
  26. if cat['id'] == id:
  27. return cat
  28. api.abort(404)

apis.__init__ 模块应该用于整合他们:

  1. from flask_restplus import Api
  2. from .namespace1 import api as ns1
  3. from .namespace2 import api as ns2
  4. # ...
  5. from .namespaceX import api as nsX
  6. api = Api(
  7. title='My Title',
  8. version='1.0',
  9. description='A description',
  10. # All API metadatas
  11. )
  12. api.add_namespace(ns1)
  13. api.add_namespace(ns2)
  14. # ...
  15. api.add_namespace(nsX)

你可以在注册API的时候为你的命名空间添加 网址前缀(url-prefixes) 。你不需要在定义命名空间对象的时候指定 网址前缀(url-prefixes)

  1. from flask_restplus import Api
  2. from .namespace1 import api as ns1
  3. from .namespace2 import api as ns2
  4. # ...
  5. from .namespaceX import api as nsX
  6. api = Api(
  7. title='My Title',
  8. version='1.0',
  9. description='A description',
  10. # All API metadatas
  11. )
  12. api.add_namespace(ns1, path='/prefix/of/ns1')
  13. api.add_namespace(ns2, path='/prefix/of/ns2')
  14. # ...
  15. api.add_namespace(nsX, path='/prefix/of/nsX')

用这种模式,你只需要在 app.py 中这样注册你的API即可:

  1. from flask import Flask
  2. from apis import api
  3. app = Flask(__name__)
  4. api.init_app(app)
  5. app.run(debug=True)

使用蓝图

查看Flask文档中的 “使用蓝图进行模块化编程( Modular Applications with Blueprints)” 以了解什么是蓝图和为什么使用蓝图。以下是一个将 Api 链接到 蓝图(Blueprint) 上的例子:

  1. from flask import Blueprint
  2. from flask_restplus import Api
  3. blueprint = Blueprint('api', __name__)
  4. api = Api(blueprint)
  5. # ...

使用蓝图将使你可以将你的API挂载到任何网址前缀(url-prefixes)下,如/或你的应用程序的子域名:

  1. from flask import Flask
  2. from apis import blueprint as api
  3. app = Flask(__name__)
  4. app.register_blueprint(api, url_prefix='/api/1')
  5. app.run(debug=True)

提示:

由于在注册蓝图的时候会处理应用程序的路由设置,所以不需要调用 Api.init_app()

提示:

在使用蓝图时,请记住调用 url_for() 时加上蓝图名:

  1. # without blueprint
  2. url_for('my_api_endpoint')
  3. # with blueprint
  4. url_for('api.my_api_endpoint')

具有可重用名称空间的多个API(Multiple APIs with reusable namespaces)

有时候你可能需要维护一个API的多个版本。如果你使用的时命名空间来搭建你的API,那么将其扩展成多个API是个很简单的事情。

根据先前的布局,我们可以将其迁移到以下目录结构:

  1. project/
  2. ├── app.py
  3. ├── apiv1.py
  4. ├── apiv2.py
  5. └── apis
  6. ├── __init__.py
  7. ├── namespace1.py
  8. ├── namespace2.py
  9. ├── ...
  10. └── namespaceX.py

每个 apivX.py 都拥有如下的结构:

  1. from flask import Blueprint
  2. from flask_restplus import Api
  3. api = Api(blueprint)
  4. from .apis.namespace1 import api as ns1
  5. from .apis.namespace2 import api as ns2
  6. # ...
  7. from .apis.namespaceX import api as nsX
  8. blueprint = Blueprint('api', __name__, url_prefix='/api/1')
  9. api = Api(blueprint
  10. title='My Title',
  11. version='1.0',
  12. description='A description',
  13. # All API metadatas
  14. )
  15. api.add_namespace(ns1)
  16. api.add_namespace(ns2)
  17. # ...
  18. api.add_namespace(nsX)

app 将这样挂载它们:

  1. from flask import Flask
  2. from api1 import blueprint as api1
  3. from apiX import blueprint as apiX
  4. app = Flask(__name__)
  5. app.register_blueprint(api1)
  6. app.register_blueprint(apiX)
  7. app.run(debug=True)

这些只是建议,你可以根据你的需求随意修改。查看 github repository examples folder 获取更多完整实例。

完整实例

下面是 TodoMVC 的完整API实例:

  1. from flask import Flask
  2. from flask_restplus import Api, Resource, fields
  3. from werkzeug.contrib.fixers import ProxyFix
  4. app = Flask(__name__)
  5. app.wsgi_app = ProxyFix(app.wsgi_app)
  6. api = Api(app, version='1.0', title='TodoMVC API',
  7. description='A simple TodoMVC API',
  8. )
  9. ns = api.namespace('todos', description='TODO operations')
  10. todo = api.model('Todo', {
  11. 'id': fields.Integer(readonly=True, description='The task unique identifier'),
  12. 'task': fields.String(required=True, description='The task details')
  13. })
  14. class TodoDAO(object):
  15. def __init__(self):
  16. self.counter = 0
  17. self.todos = []
  18. def get(self, id):
  19. for todo in self.todos:
  20. if todo['id'] == id:
  21. return todo
  22. api.abort(404, "Todo {} doesn't exist".format(id))
  23. def create(self, data):
  24. todo = data
  25. todo['id'] = self.counter = self.counter + 1
  26. self.todos.append(todo)
  27. return todo
  28. def update(self, id, data):
  29. todo = self.get(id)
  30. todo.update(data)
  31. return todo
  32. def delete(self, id):
  33. todo = self.get(id)
  34. self.todos.remove(todo)
  35. DAO = TodoDAO()
  36. DAO.create({'task': 'Build an API'})
  37. DAO.create({'task': '?????'})
  38. DAO.create({'task': 'profit!'})
  39. @ns.route('/')
  40. class TodoList(Resource):
  41. '''Shows a list of all todos, and lets you POST to add new tasks'''
  42. @ns.doc('list_todos')
  43. @ns.marshal_list_with(todo)
  44. def get(self):
  45. '''List all tasks'''
  46. return DAO.todos
  47. @ns.doc('create_todo')
  48. @ns.expect(todo)
  49. @ns.marshal_with(todo, code=201)
  50. def post(self):
  51. '''Create a new task'''
  52. return DAO.create(api.payload), 201
  53. @ns.route('/<int:id>')
  54. @ns.response(404, 'Todo not found')
  55. @ns.param('id', 'The task identifier')
  56. class Todo(Resource):
  57. '''Show a single todo item and lets you delete them'''
  58. @ns.doc('get_todo')
  59. @ns.marshal_with(todo)
  60. def get(self, id):
  61. '''Fetch a given resource'''
  62. return DAO.get(id)
  63. @ns.doc('delete_todo')
  64. @ns.response(204, 'Todo deleted')
  65. def delete(self, id):
  66. '''Delete a task given its identifier'''
  67. DAO.delete(id)
  68. return '', 204
  69. @ns.expect(todo)
  70. @ns.marshal_with(todo)
  71. def put(self, id):
  72. '''Update a task given its identifier'''
  73. return DAO.update(id, api.payload)
  74. if __name__ == '__main__':
  75. app.run(debug=True)

你可以在 github repository examples folder 获取更多完整实例。