Last active
April 19, 2023 22:31
-
-
Save hheimbuerger/57476006c35495690285f2fd1aa4fc9d to your computer and use it in GitHub Desktop.
Flask app with long-running startup code, that blocks incoming requests until initialization is complete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import concurrent.futures | |
from functools import wraps | |
from flask import Flask | |
data = None | |
def long_running_initialization(): | |
# Long running initialization code goes here | |
print('Initializing...') | |
for i in range(1, 30): | |
import time; time.sleep(1) | |
print(f' ... still initializing {i}s') | |
global data; data = 42 | |
print('Initialization complete!') | |
def ensure_initialized(f): | |
""" | |
A convenience view decorator that waits for the initialization to complete. | |
""" | |
@wraps(f) | |
def decorated_function(*args, **kwargs): | |
# run initialization code, possibly blocking if necessary | |
concurrent.futures.wait([initialization_future]) | |
# return back to decorated view function | |
return f(*args, **kwargs) | |
return decorated_function | |
# create Flask app -- this apparently needs to happen before the executor is created | |
app = Flask(__name__) | |
# create executor -- we only need a single worker, because we only want to run a single task on it ever | |
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) | |
# the initialization will take a long time, so kick it off asap, whether there's incoming requests or not! | |
initialization_future = executor.submit(long_running_initialization) | |
@app.route('/') | |
@ensure_initialized # this ensures that any requests will block until the initialization has completed | |
def access_data(): | |
# now we can access the fully initialized data set | |
global data | |
return f'Data: {data}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment