Performance: Command pattern with Flask CLI
This affects the startup time and responsiveness of the Flask CLI commands, impacting how quickly commands execute and return results.
import click from flask import Flask app = Flask(__name__) @app.cli.command() @click.pass_context def cleanup(ctx): import time # Import inside command to delay cost time.sleep(1) # Simulate work only when command runs print('Cleanup done')
import click from flask import Flask # Heavy imports and operations at global scope import time time.sleep(5) # Simulate slow startup app = Flask(__name__) @app.cli.command() def cleanup(): print('Cleanup done')
| Pattern | Import Timing | Startup Delay | Execution Delay | Verdict |
|---|---|---|---|---|
| Heavy global imports | At CLI start | High (blocks startup) | Low | [X] Bad |
| Lazy imports inside command | At command run | Low (fast startup) | Moderate | [OK] Good |
@app.cli.command decorator to register custom CLI commands.flask greet?
import click
from flask import Flask
app = Flask(__name__)
@app.cli.command()
@click.argument('name')
def greet(name):
click.echo(f'Hello, {name}!')greet requires a positional argument name due to @click.argument('name').flask greet without providing name will cause Click to raise an error about the missing argument.from flask import Flask
app = Flask(__name__)
@app.cli.command()
def hello():
print('Hello from CLI')
if __name__ == '__main__':
app.run()app.run() starts the Flask web server and is not needed or appropriate in CLI command files.flask command, so running app.run() here will start the server unnecessarily and block CLI commands.with app.app_context() inside the command function.Pass the test and this pattern moves unknown