How to process data before storing in a database on the eve of python

I am currently looking into python eve framework and mongoDB database to create full API development. The day before, basic CRUD operations are done only by defining a schema in a file settings.py

. The client can send GET / POST methods and the data is automatically saved to mongoDB according to a predefined schema.

What if I want to preprocess the data before inserting it into mongoDB (ex: the client only sends the quantity and price of the product, then the server calculates the total and stores the product, price and amount in the database). And what if I want to process my data before responding to the client. Should we use flask controller methods (like EVE - define custom flask controllers) and manually save the data to the database?

+3


source to share


1 answer


You are asking two things here.

Firstly, if you want to manipulate the data that have already been saved to a response to a GET request, you need on_fetched_resource_<resource_name>

and on_fetched_item_<resource_name>

interceptors database events. You can add the information you want to get there before it returns:

When the GET, POST, PATCH, PUT, DELETE methods have been executed, the on_post_ and on_post__ event is called. You can subscribe to these events with multiple callback functions. The callbacks will receive the available resource, the 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()    

      



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

But if you want to process the POST data before storing it in the database, then you need an event hook on_insert_<resource_name>

. You can add the information you want to provide there before storing it in the database:

Database event interceptors work like request event interceptors. These events are fired before and after the database action. Below is an example of setting up events:

def add_sum(items):
    for item in items:
        item['sum'] = item['a'] + item['b']

app = Eve()
app.on_insert_item += add_sum

      

+4


source







All Articles