我正在尝试在我的flask应用程序中实现一个路由来提供给定资源的OPTIONS方法,并返回与所述资源相关联的marshmallow模式的描述。类似于django的东西:
{
"name": "Dataset List",
"description": "",
"renders": [
"application/json",
"text/html"
],
"parses": [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data"
],
"actions": {
"POST": {
"id": {
"type": "integer",
"required": false,
"read_only": true,
"label": "ID"
},
"url": {
"type": "field",
"required": false,
"read_only": true,
"label": "Url"
},
"name": {
"type": "string",
"required": true,
"read_only": false,
"label": "Name",
"help_text": "The dataset name.",
"max_length": 256
}
}
}
}
我似乎无法在Schema
或返回此描述的文档中找到任何方法,并且AlbumSchema.opts.fields
为空。是否可以遍历整个字段并构建我需要的描述?有点像:
desc = {f: {"required": f.required,
"type": f.__class__.__name__,
...}
for f in AlbumSchema.fields}
感谢@Pop,我设法找到了解决方案。 首先,我声明了一个通用选项方法:
class DescriptiveMethodView(views.MethodView):
name = description = uri = doc_uri = None
def options(self, id=None):
"""Base Options View.
---
description: retrieve options available for this resource.
responses:
200:
name: description
type: object
"""
d = spec.to_dict()
info = {'name': self.name,
'description': self.description % {'id': id or 'model'}}
return jsonify(info=info,
definitions=d['definitions'],
actions=d['paths'][self.doc_uri])
然后我只是从它继承并覆盖这些类属性:
class FooView(DescriptiveMethodView):
name = 'Foos'
description = 'all Foos in the dataset'
doc_uri = uri = '/foo'
class BarView(DescriptiveMethodView):
name = 'Bar'
description = 'A bar in the dataset in the dataset'
uri = '/bar/<id>'
doc_uri = '/bar/{id}'