How to process data before storing to database in python eve How to process data before storing to database in python eve flask flask

How to process data before storing to database in python eve


You are asking two things here.

First, if you want to manipulate data already stored before responding to GET requests, what you need is on_fetched_resource_<resource_name> and on_fetched_item_<resource_name> database event hooks. You can add there the information you want to the response before it is returned:

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_callbackapp.on_post_GET_contacts += post_contacts_get_callbackapp.run()    

See documentation here: http://python-eve.org/features.html#post-request-event-hooks

But if you want to process POST data before storing in database what you need is a on_insert_<resource_name> database event hook. You can add there the information you want to the resource before it is saved at database:

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