Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to process data before storing to database in python eve

I'm currently learning python eve framework and mongoDB database for restful API development. In eve, basic CRUD operations are done only by defining the schema in settings.py file. Client can send GET/POST methods and data is automatically stored into mongoDB according to the predefined schema.

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

like image 1000
Min Htet Oo Avatar asked Jun 08 '17 08:06

Min Htet Oo


1 Answers

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_callback
app.on_post_GET_contacts += post_contacts_get_callback

app.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
like image 76
gcw Avatar answered Sep 21 '22 21:09

gcw