使用Python eve 时如何添加一些自身进程?

How to add some self process when using Python eve?

如何在使用Python eve 时添加一些自身进程?

例如,这是我的 activity 架构。

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 创建 activity 时生成一个共享 url 和二维码,并给它一个简单的 ID,比如 001,我已经实现了生成类似二维码生成器的代码,但我不知道如何在信息被 POSTed 之后和保存到 MongoDB.

之前添加所有这些功能

我看过类似事件挂钩的东西,但我仍然不知道如何实现它,比如修复 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

第二种方法使每个回调函数都超级专业化并改进代码隔离。还要记住,您可以将多个回调挂接到同一事件(因此是一元运算符。)

有关参考,请参阅 the docs