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
import smtplib from email.message import EmailMessage from threading import Thread
Sending welcome emails off the request thread in Flask
background-threads
app-context
email
Intermediate
8 steps
python
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.shortcuts import get_object_or_404 from django.views.generic import DetailView
Team membership access control in Django
access-control
mixins
class-based-views
Intermediate
7 steps
python
import uuid from pathlib import Path from fastapi import APIRouter, File, Form, HTTPException, UploadFile
Handling multipart file uploads in FastAPI
file-upload
validation
multipart-form
Intermediate
6 steps
typescript
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, DeepPartial } from 'typeorm'; import { User } from './entities/user.entity';
Building a CRUD service in NestJS
crud
dependency-injection
repository-pattern
Intermediate
7 steps
python
from copy import deepcopy from typing import Any, Mapping
How a recursive deep merge works in Python
recursion
immutability
dictionaries
Intermediate
6 steps
python
from difflib import SequenceMatcher from bisect import bisect_left, bisect_right
Building a fuzzy autocomplete matcher
fuzzy-matching
binary-search
ranking
Intermediate
9 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.