I was wondering if there was a way to ensure some function was called in all Flask API endpoints without manually calling the function? This is to prevent repetition in making sure the functions get called, and to avoid mistakes of accidentally forgetting to call it. Maybe with a library or decorator?
def do_something(): # does things # does more things @app.route(/route1) Method = [GET] def my_function(): do_something() return 200 @app.route(/route2) Method = [GET] def my_other_function(): do_something() return 200
So i want
def do_something(): # does things # does more things @do_something_was_called @app.route(/route1) Method = [GET] def my_function(): return 200 @do_something_was_called @app.route(/route2) Method = [GET] def my_other_function(): return 200
Thanks in advance!
Advertisement
Answer
You can use app.before_request
From the doc
before_request(f)
Register a function to run before each request. For example, this can be used to open a database connection, or to load the logged in user from the session.
example:
@app.before_request def load_user(): if "user_id" in session: g.user = db.session.get(session["user_id"])