使用Python eve时如何添加一些自我过程?
例如,这是我的活动架构。
schema = {
'id': {
'type': 'integer',
'readonly': True,
'unique': True,
},
'name': {
'type': 'string',
'minlength': 3,
'maxlength': 20,
'required': True,
},
'date': {
'type': 'datetime',
},
'location': {
'type': 'string',
},
'icon': {
'type': 'media',
},
'type': {
'type': 'integer',
'allowed': [i for i in range(5)],
},
'info': {
'type': 'list',
},
'share': {
'type': 'dict',
'readonly': True,
'schema': {
'url': {
'type': 'string',
},
'qr': {
'type': 'media',
}
}
},
'publisher': {
'type': 'list',
},
'participators': {
'type': 'list',
},
}
而且我想在使用POST创建活动时生成共享网址和qr代码,并给它一个简单的ID(如001),我已经实现了生成类似qr代码生成器之类的代码,但是我不知道如何在要发布的信息之后和保存到MongoDB之前添加所有这些功能。
我见过类似Event Hook的东西,但我仍然不知道如何实现,例如修复POST数据或其他功能。
您能给我看一些数据示例吗,非常感谢。
该on_insert
事件被触发后,该POST
请求已被验证,解析和之前的文件被发送到数据库。您可以挂钩回调函数on_insert
并根据需要操纵有效负载,如下所示:
from eve import Eve
def manipulate_inbound_documents(resource, docs):
if resource == 'activity':
for doc in docs:
doc['id_field'] = '001'
doc['qr'] = 'mycqcode'
app = Eve()
app.on_insert += manipulate_inbound_documents
if __name__ == '__main__':
app.run()
您还可以使用on_insert_<resourcename>
,如下所示:
# note that the signature has changed
def manipulate_inbound_documents(docs):
# no need to branch on the resource name
for doc in docs:
doc['id_field'] = '001'
doc['qr'] = 'mycqcode'
app = Eve()
# only fire the event on 'activity' endpoint
app.on_insert_activity += manipulate_inbound_documents
第二种方法使每个回调函数都超级专门化,并改善了代码隔离性。还要记住,您可以将多个回调连接到同一个事件(因此,一元运算符)。
供参考,请参阅文档
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句