Bird
0
0

You want to create a Flask CLI command that prints all user names from a database. Which approach correctly uses the command pattern with app context?

hard📝 Application Q15 of 15
Flask - Ecosystem and Patterns
You want to create a Flask CLI command that prints all user names from a database. Which approach correctly uses the command pattern with app context?
AUse @app.cli.command and inside the function, query users within a with app.app_context() block
BUse @app.route to define the command and query users directly
CDefine a function without decorators and call it from main
DUse @click.command without app context and query users
Step-by-Step Solution
Solution:
  1. Step 1: Understand Flask CLI command with app context

    Commands need Flask app context to access database and app features, so use with app.app_context() inside the command function.
  2. Step 2: Evaluate options

    @app.route is for web routes, not CLI commands. Calling functions without decorators won't register CLI commands. Using @click.command alone lacks app context, causing errors.
  3. Final Answer:

    Use @app.cli.command and inside the function, query users within a with app.app_context() block -> Option A
  4. Quick Check:

    CLI commands need app context for DB access [OK]
Quick Trick: Wrap DB queries in app.app_context() inside CLI commands [OK]
Common Mistakes:
MISTAKES
  • Using @app.route for CLI commands
  • Forgetting app context for DB access
  • Not registering commands with decorators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Flask Quizzes