Bird
0
0

Why might this Flask application factory code cause a runtime error?

medium📝 Debug Q7 of 15
Flask - Ecosystem and Patterns
Why might this Flask application factory code cause a runtime error?
def create_app():
    app = Flask(__name__)
    @app.route('/home')
    def home():
        return 'Welcome'
    return app

app = create_app()
app.run()
AFlask app must be created globally, not inside a function
BDefining routes inside the factory function is not allowed
CReturning app before defining routes causes missing endpoints
DCalling app.run() outside the factory without checking __name__ == '__main__'
Step-by-Step Solution
Solution:
  1. Step 1: Analyze app.run() usage

    Calling app.run() directly executes the server immediately.
  2. Step 2: Check for __main__ guard

    Best practice is to call app.run() inside if __name__ == '__main__' block to avoid errors when importing.
  3. Step 3: Evaluate other options

    Defining routes inside factory is valid. Returning app after routes is correct. Creating app inside function is standard.
  4. Final Answer:

    Calling app.run() outside the factory without checking __name__ == '__main__' -> Option D
  5. Quick Check:

    Is app.run() guarded by __main__? No. [OK]
Quick Trick: Always guard app.run() with if __name__ == '__main__' [OK]
Common Mistakes:
MISTAKES
  • Thinking routes can't be inside factory
  • Assuming app must be global
  • Returning app before route definitions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes