将计算字段添加到eve架构

时间:2016-07-20 11:23:02

标签: eve

有没有办法将自己的计算字段放入模式中,可以使用在flask中的before_output事件中计算的值来填充,或者其他什么?

schema = {
    # Schema definition, based on Cerberus grammar. Check the Cerberus project
    # (https://github.com/nicolaiarocci/cerberus) for details.
    'firstname': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 10,
    },
    'lastname': {
        'type': 'string',
        'minlength': 1,
        'maxlength': 15,
        'required': True,
        # talk about hard constraints! For the purpose of the demo
        # 'lastname' is an API entry-point, so we need it to be unique.
        'unique': True,
    },
    # 'role' is a list, and can only contain values from 'allowed'.
    'role': {
        'type': 'list',
        'allowed': ["author", "contributor", "copy"],
    },
    # An embedded 'strongly-typed' dictionary.
    'location': {
        'type': 'dict',
        'schema': {
            'address': {'type': 'string'},
            'city': {'type': 'string'}
        },
    },
    'born': {
        'type': 'datetime',
    },
    'calculated_field': {
        'type': 'string',
    }
}

并使用自己的mongodb查询语句填充calculated_field。

1 个答案:

答案 0 :(得分:2)

  1. 更新您的设置,以便将您的字段标记为只读:'calculated_field': {'readonly': True}。这将防止客户意外写入字段。可能不需要将其设置为字符串类型;
  2. 向启动脚本添加回调函数。这将处理出站文档,在只读字段中注入计算值;
  3. 将您的回调附加到应用程序的on_fetched事件。
  4. 启动该应用程序。
  5. 所以你的脚本可能看起来像:

    from eve import Eve
    
    # the callback function
    def add_calculated_field_value(resource, response):                                          
        for doc in response['_items']:                                                    
            doc['calculated_field'] = 'hello I am a calculated field'
    
    # instantiate the app and attach the callback function to the right event
    app = Eve()
    app.on_fetched_resource += add_calculated_field_value
    
    if __name__ == '__main__':
        app.run()