有没有办法将自己的计算字段放入模式中,可以使用在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。
答案 0 :(得分:2)
'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()