1

我在需要与 telnet 设备通信并返回结果的 eve 应用程序中有一些自定义烧瓶方法,但我还想在从该 telnet 设备检索数据后将数据预填充到一些资源中,如下所示:

@app.route("/get_vlan_description", methods=['POST'])
def get_vlan_description():
    switch = prepare_switch(request)
    result = dispatch_switch_command(switch, 'get_vlan_description')

    # TODO: populate vlans resource with result data and return status

我的 settings.py 看起来像这样:

SERVER_NAME = '127.0.0.1:5000'
DOMAIN = {
    'vlans': {
        'id': {
            'type': 'integer',
            'required': True,
            'unique': True
        },
        'subnet': {
            'type': 'string',
            'required': True
        },
        'description': {
            'type': 'boolean',
            'default': False
        }
    }
}

我无法找到有关如何直接访问 mongo 资源并插入此数据的文档或源代码。

4

2 回答 2

5

你看过on_insert钩子吗?从文档中:

当文档即将存储在数据库中时,会引发on_insert(resource, documents)on_insert_<resource>(documents)事件。回调函数可以挂钩这些事件以任意添加新字段或编辑现有字段on_insert在每个正在更新的资源上on_insert_<resource>引发,而在<resource>端点被 POST 请求命中时引发。在这两种情况下,仅当至少一个文档通过验证并将被插入时才会引发该事件。documents是一个列表,仅包含准备插入的文档(不包括未通过验证的有效负载文档)

所以,如果我得到你想要达到的目标,你可以有这样的东西:

def telnet_service(resource, documents):
    """ 
        fetch data from telnet device;
        update 'documents' accordingly 
    """
    pass

app = Eve()
app.on_insert += telnet_service

if __name__ == "__main__":
    app.run()

请注意,这样您就不必直接弄乱数据库,因为 Eve 会处理这个问题。

如果您不想存储 telnet 数据而只想将其与获取的文档一起发回,您可以on_fetch改为 hook to。

最后,如果您真的想使用数据层,您可以使用此示例代码段app.data.driver中所见。

于 2014-02-19T07:02:45.573 回答
0

使用post_internal

用法示例

from run import app
from eve.methods.post import post_internal

payload = {
    "firstname": "Ray",
    "lastname": "LaMontagne",
    "role": ["contributor"]
}

with app.test_request_context():
    x = post_internal('people', payload)
    print(x)
于 2018-05-24T09:47:32.237 回答