gpt4 book ai didi

python - 如何在 python-eve 应用程序中进行自定义插入

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:47 26 4
gpt4 key购买 nike

我在 eve 应用程序中有一些自定义的 flask 方法需要与 telnet 设备通信并返回结果,但我也想在从此 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 资源并插入此数据的文档或源代码。

最佳答案

你看过 on_insert 吗?钩?来自文档:

When documents are about to be stored in the database, both on_insert(resource, documents) and on_insert_<resource>(documents) events are raised. Callback functions could hook into these events to arbitrarily add new fields, or edit existing ones. on_insert is raised on every resource being updated while on_insert_<resource> is raised when the <resource> endpoint has been hit with a POST request. In both circumstances, the event will be raised only if at least one document passed validation and is going to be inserted. documents is a list and only contains documents ready for insertion (payload documents that did not pass validation are not included).

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

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 数据,而只想将其与获取的文档一起发回,您可以 Hook on_fetch 相反。

最后,如果你真的想使用数据层,你可以使用 app.data.driverthis example snippet 中所示.

关于python - 如何在 python-eve 应用程序中进行自定义插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21865900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com