将计算字段添加到 eve 模式
add a calculated field to eve schema
有没有办法将自己的计算字段带入架构中,该架构可以填充在来自 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',
}
}
并且 calculated_field 使用自己的 mongodb 查询语句填充。
- 更新您的设置,以便将您的字段标记为只读:
'calculated_field': {'readonly': True}
。这将防止客户端意外写入该字段。将其设置为字符串类型可能没有必要;
- 向启动脚本添加回调函数。这将处理出站文档,在您的只读字段中注入计算值;
- 将您的回调附加到应用程序的
on_fetched
事件。
- 启动应用程序。
因此您的脚本可能类似于:
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()
有没有办法将自己的计算字段带入架构中,该架构可以填充在来自 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',
}
}
并且 calculated_field 使用自己的 mongodb 查询语句填充。
- 更新您的设置,以便将您的字段标记为只读:
'calculated_field': {'readonly': True}
。这将防止客户端意外写入该字段。将其设置为字符串类型可能没有必要; - 向启动脚本添加回调函数。这将处理出站文档,在您的只读字段中注入计算值;
- 将您的回调附加到应用程序的
on_fetched
事件。 - 启动应用程序。
因此您的脚本可能类似于:
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()