Bird
0
0

Why does this Flask async task code cause an error?

medium📝 Debug Q7 of 15
Flask - Background Tasks
Why does this Flask async task code cause an error?
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    import asyncio
    asyncio.run(background_task())
    return 'Done'

def background_task():
    print('Running')
AFlask does not support any async code.
Bbackground_task() must be decorated with @app.task.
CThe print statement is not allowed in async functions.
Dasyncio.run() cannot be called inside an already running event loop like Flask's.
Step-by-Step Solution
Solution:
  1. Step 1: Understand asyncio.run() usage

    asyncio.run() starts a new event loop and cannot be called inside an existing one.
  2. Step 2: Recognize Flask's event loop context

    Flask may already run inside an event loop, so calling asyncio.run() inside route causes error.
  3. Final Answer:

    asyncio.run() cannot be called inside an already running event loop like Flask's. -> Option D
  4. Quick Check:

    asyncio.run() inside event loop causes error [OK]
Quick Trick: Don't call asyncio.run() inside Flask route [OK]
Common Mistakes:
MISTAKES
  • Thinking Flask disallows all async code
  • Believing print is invalid in async
  • Confusing Flask tasks with Celery tasks

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes