flask: post data after insert, delete and update in database
Question:
I want to post data to a target url after insertion, updation and deletion in a model in flask like rest-hooks in django. for now i have only found signal events of flask-sqlalchemy like below:
@event.listens_for(MyModel, 'after_insert')
def do_stuff(mapper, connection, target):
So how to do this in flask like we do using rest-hooks in Django or is there any other library which i can use.
Thanks in advance.
Answers:
I am assuming your REST end-point where you want to POST to is in the same flask application. It is a good practice to separate out the business logic in your REST end-points and share the code across your whole application.
In my case, I usually create separate py files (called them services) and move the business logic there:
# inventory_services.py
def delete_item(id, data):
pass
# ... business logic here
Then call this method from your REST end-point where you POST data to:
from inventory_services import delete_item
@api.route('/inventory/delete-item', methods=['POST'])
def delete_item_api():
posted_data = request.get_json()
delete_item(posted_data.id, posted_data.data)
Use the same service methods in your SQL Alchemy hook methods:
from inventory_services import delete_item
@event.listens_for(MyModel, 'after_insert')
def do_stuff(mapper, connection, target):
delete_item(id, data)
The basic idea here is to move the code in your api methods to other plain functions so that they will be accessible across your whole application.
I want to post data to a target url after insertion, updation and deletion in a model in flask like rest-hooks in django. for now i have only found signal events of flask-sqlalchemy like below:
@event.listens_for(MyModel, 'after_insert')
def do_stuff(mapper, connection, target):
So how to do this in flask like we do using rest-hooks in Django or is there any other library which i can use.
Thanks in advance.
I am assuming your REST end-point where you want to POST to is in the same flask application. It is a good practice to separate out the business logic in your REST end-points and share the code across your whole application.
In my case, I usually create separate py files (called them services) and move the business logic there:
# inventory_services.py
def delete_item(id, data):
pass
# ... business logic here
Then call this method from your REST end-point where you POST data to:
from inventory_services import delete_item
@api.route('/inventory/delete-item', methods=['POST'])
def delete_item_api():
posted_data = request.get_json()
delete_item(posted_data.id, posted_data.data)
Use the same service methods in your SQL Alchemy hook methods:
from inventory_services import delete_item
@event.listens_for(MyModel, 'after_insert')
def do_stuff(mapper, connection, target):
delete_item(id, data)
The basic idea here is to move the code in your api methods to other plain functions so that they will be accessible across your whole application.