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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Registering a command under app.cli lets you script database tasks that run inside the app context.
- 2Batching inserts and committing once at the end keeps seeding fast and atomic.
- 3Faker plus Click options make sample data both realistic and configurable from the terminal.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-flask-seed-command-with-click-explained-python-98c4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.