在OPTIONS方法中显示marshmallow Schema的描述

时间:2018-02-27 15:09:29

标签: python rest flask marshmallow

我正在尝试在我的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}

1 个答案:

答案 0 :(得分:0)

感谢@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}'
相关问题