【问题标题】:How to add some self process when using Python eve?使用 Python eve 时如何添加一些自我进程?
【发布时间】:2015-04-09 05:39:31
【问题描述】:

使用 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 创建活动时生成一个共享 url 和二维码,并给它一个简单的 ID,比如 001,我已经实现了生成类似二维码生成器的代码,但我没有t 如何在要发布的信息之后和保存到 MongoDB 之前添加所有这些功能。

我见过类似事件挂钩的东西,但我仍然不知道如何实现它,比如修复 POST 数据或其他一些功能。

你能给我看一些数据示例吗,非常感谢。

【问题讨论】:

    标签: python flask eve


    【解决方案1】:

    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

    【讨论】:

    • 但是这种方式只是改变了对用户的响应,但是实际保存在db中的仍然是我们的请求得到的,不是吗?我实际上需要一些方法来修复数据,就像我在名称字段中得到“John”一样,我想保存一个像“t.co/john”这样的链接。所以我必须使用 request.args.get() 来获取 John,然后使用 pymongo 将数据插入到 Mongo 中,对吗?我其实迷茫了很久。
    • 不,因为您正在更改有效负载发送到数据库之前,您也在更改数据库文档。
    • 完美,我建议您将此示例和说明添加到您的文档中,它肯定会帮助很多其他人。
    猜你喜欢
    • 2014-03-18
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多