Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hheimbuerger/57476006c35495690285f2fd1aa4fc9d to your computer and use it in GitHub Desktop.
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
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