Issue
In my python3 flask application I would like to execute a couple of recurring tasks before the first request.
In order to achieve this, I want to make use of the@app.before_first_request_funcs
.
Can anyone please give me an example usage of @app.before_first_request_funcs
?
Here is my sample code:
import threading
import time
from flask import Flask
app = Flask(__name__)
def activate_job():
def run_job():
while True:
print("recurring task")
time.sleep(3)
thread = threading.Thread(target=run_job())
thread.start()
def activate_job2():
def run_job2():
while True:
print("recurring task2")
time.sleep(3)
thread = threading.Thread(target=run_job2())
thread.start()
@app.after_first_request(activate_job())
@app.before_first_request(activate_job2())
@app.route('/')
def home():
return {"action": "This has done something"}
if __name__ == '__main__':
print(app.before_first_request_funcs)
app.run()
Solution
As per the documentation, you should use @app.before_first_request
to do what you want.
from flask import Flask
app = Flask(__name__)
def some_func(some_arg):
print('coucou')
# @app.before_first_request(some_func)
@app.route('/')
def home():
return {"action" : "This has done something"}
if __name__ == '__main__':
print(app.before_first_request_funcs)
app.run()
You can see the behavior of the method before_first_request_funcs
that is not a decorator by commenting and uncommenting the decorator before_first_request
.
If it is commented, it'll print an empty list, and if you uncomment the line, it'll return a list of one element containing the function some_func
object (for me, it was [<function some_func at 0x0000021393A0AD90>]
).
Answered By - IMCoins
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.