Performance: Calling tasks asynchronously
This concept affects how quickly the main web request responds by offloading long tasks to run separately, improving user experience and server responsiveness.
from flask import Flask, request from threading import Thread app = Flask(__name__) def async_task(): long_task() @app.route('/process') def process(): Thread(target=async_task).start() return "Task started asynchronously"
from flask import Flask, request app = Flask(__name__) @app.route('/process') def process(): # Long task runs synchronously result = long_task() return f"Task done: {result}"
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous long task | Minimal | 0 | Blocks response delaying paint | [X] Bad |
| Asynchronous task with thread | Minimal | 0 | Immediate response enables fast paint | [OK] Good |
from threading import Thread
from flask import Flask
app = Flask(__name__)
def background_task():
print('Task done')
@app.route('/')
def index():
Thread(target=background_task).start()
return 'Hello'from threading import Thread
from flask import Flask
app = Flask(__name__)
def task():
print(app.name)
@app.route('/')
def index():
Thread(target=task).start()
return 'Done'with app.app_context(): inside the task ensures context is active during task execution.with app.app_context(): inside the background task function. -> Option APass the test and this pattern moves unknown