gpt4 book ai didi

python 夏娃 : Use Pre-Request Event Hooks to modify data before inserting to DB

转载 作者:可可西里 更新时间:2023-11-01 09:11:19 24 4
gpt4 key购买 nike

我通过在我的 eve-API 上执行 POST 请求将新数据添加到我的数据库中。由于需要从 Python 端添加一些数据,我想我可以使用 pre-request event hook 添加这些数据。 .

那么有没有办法在将数据插入数据库之前使用预请求 Hook 修改 POST 请求中包含的数据?我已经了解如何实现这样的 Hook ,但对如何在插入数据库之前修改数据一无所知。

最佳答案

您可能想看看 database hooks ,具体在 insert hooks :

When a POST requests hits the API and new items are about to be stored in the database, these vents are fired:

on_insert for every resource endpoint.

on_insert_<resource_name> for the specific resource endpoint.

Callback functions could hook into these events to arbitrarily add new fields or edit existing ones.

在下面的代码中:

def before_insert(resource_name, documents):
if resource_name == 'myresource':
for document in documents:
document['field'] = 'value'

app = Eve()
app.on_insert += before_insert

app.run()

每次 POST 命中 API 时 before_insert函数被调用。函数更新field1对于每个文档。由于此回调是在有效负载发送到数据库之前调用的,因此更改将持久保存到数据库中。

一个有趣的选择是:

def before_insert(resource_name, documents):
for document in documents:
document['field'] = 'value'

app = Eve()
app.on_insert_myresource += before_insert

app.run()

在回调中我们不再测试端点名称。这是因为我们将回调 Hook 到 on_insert_myresoure。事件,因此只有在对 myresource 执行 POST 请求时才会调用该函数端点。关注点分离更好,代码更简单,性能也得到提高,因为回调不会被所有 API 插入命中。旁注,最终您可以将多个回调挂接到同一个事件(因此使用加法运算符 += )。

关于 python 夏娃 : Use Pre-Request Event Hooks to modify data before inserting to DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34118224/

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