Flask · Lesson 13 of 15
The Flask CLI and Shell
Custom flask commands, the shell context and one-off scripts.
- Advanced
- 12 min read
- 3 objectives
Before this lessonLesson 12: Caching and Background Jobs
What you will learn
- Add a CLI command
- Expose models to flask shell
- Run a seed script
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
The flask command is the right place for one-off admin tasks: seed data, create an admin, print stats.
A custom command
import click
from flask.cli import with_appcontext
@click.command("seed")
@with_appcontext
def seed():
if User.query.filter_by(email="ada@example.com").first():
click.echo("already seeded")
return
u = User(email="ada@example.com")
u.set_password("change-me")
db.session.add(u)
db.session.commit()
click.echo("seeded ada")
def create_app():
app = Flask(__name__)
...
app.cli.add_command(seed)
return appflask --app myapp seedShell context
@app.shell_context_processor
def extras():
return {"db": db, "User": User, "Post": Post}
# flask shell -> User.query.count()