python 51 lines · 7 steps

Building a Flask seed command with Click

A custom Flask CLI command fills the database with fake users and products for local development.

Explained by highlit
1import random
2 
3import click
4from faker import Faker
5 
6from app import app, db
7from app.models import Category, Product, User
8 
9fake = Faker()
10 
11 
12@app.cli.command("seed")
13@click.option("--users", default=20, help="Number of users to create.")
14@click.option("--products", default=100, help="Number of products to create.")
15@click.option("--flush/--no-flush", default=False, help="Wipe tables first.")
16def seed(users, products, flush):
17 """Populate the database with sample data."""
18 if flush:
19 click.echo("Flushing existing records...")
20 Product.query.delete()
21 Category.query.delete()
22 User.query.delete()
23 db.session.commit()
24 
25 categories = [
26 Category(name=name, slug=name.lower())
27 for name in ("Books", "Electronics", "Home", "Toys", "Garden")
28 ]
29 db.session.add_all(categories)
30 
31 with click.progressbar(range(users), label="Creating users") as bar:
32 for _ in bar:
33 user = User(email=fake.unique.email(), name=fake.name())
34 user.set_password("password")
35 db.session.add(user)
36 
37 with click.progressbar(range(products), label="Creating products") as bar:
38 for _ in bar:
39 db.session.add(
40 Product(
41 name=fake.catch_phrase(),
42 price=round(random.uniform(4.99, 499.99), 2),
43 stock=random.randint(0, 250),
44 category=random.choice(categories),
45 )
46 )
47 
48 db.session.commit()
49 click.secho(
50 f"Seeded {users} users and {products} products.", fg="green"
51 )
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Registering a command under app.cli lets you script database tasks that run inside the app context.
  2. 2Batching inserts and committing once at the end keeps seeding fast and atomic.
  3. 3Faker plus Click options make sample data both realistic and configurable from the terminal.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a Flask seed command with Click — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code