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?
JavaScript
x
14
14
1
def do_something():
2
# does things
3
# does more things
4
5
@app.route(/route1) Method = [GET]
6
def my_function():
7
do_something()
8
return 200
9
10
@app.route(/route2) Method = [GET]
11
def my_other_function():
12
do_something()
13
return 200
14
So i want
JavaScript
1
14
14
1
def do_something():
2
# does things
3
# does more things
4
5
@do_something_was_called
6
@app.route(/route1) Method = [GET]
7
def my_function():
8
return 200
9
10
@do_something_was_called
11
@app.route(/route2) Method = [GET]
12
def my_other_function():
13
return 200
14
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:
JavaScript
1
5
1
@app.before_request
2
def load_user():
3
if "user_id" in session:
4
g.user = db.session.get(session["user_id"])
5