我目前正在学习python eve框架和mongoDB数据库,以进行宁静的API开发.在前夕,只有通过在settings.py文件中定义模式才能完成基本的CRUD操作.客户端可以发送GET / POST方法,并根据预定义的模式将数据自动存储到mongoDB中.
如果我想在将数据插入mongoDB之前对其进行预处理(例如:客户端仅发送产品数量和价格,然后服务器计算总数量并将产品,价格和数量存储到数据库中),该怎么办?如果我想在响应客户端之前处理我的数据,该怎么办?我们应该使用烧瓶控制器方法(如此EVE – define custom flask controllers)并手动将数据存储到数据库中吗?
解决方法:
你在这里问两件事.
首先,如果你想在响应GET请求之前操纵已经存储的数据,你需要的是on_fetched_resource_< resource_name>和on_fetched_item_< resource_name>数据库事件挂钩.您可以在返回之前在响应中添加所需的信息:
When a GET, POST, PATCH, PUT, DELETE method has been executed, both a on_post_ and on_post__ event is raised. You can subscribe to these events with multiple callback functions. Callbacks will receive the resource accessed, original flask.request object and the response payload.
def post_get_callback(resource, request, payload):
print('A GET on the "%s" endpoint was just performed!' % resource)
def post_contacts_get_callback(request, payload):
print('A get on "contacts" was just performed!')
app = Eve()
app.on_post_GET += post_get_callback
app.on_post_GET_contacts += post_contacts_get_callback
app.run()
请参阅此处的文档:http://python-eve.org/features.html#post-request-event-hooks
但是如果你想在数据库中存储之前处理POST数据你需要的是on_insert_< resource_name>数据库事件钩子.在将资源保存到数据库之前,您可以在其中添加所需的信息:
Database event hooks work like request event hooks. These events are fired before and after a database action. Here is an example of how events are configured:
def add_sum(items):
for item in items:
item['sum'] = item['a'] + item['b']
app = Eve()
app.on_insert_item += add_sum