A shop with empty shelves
Imagine a new shop opening with empty shelves. You cannot tell if the shelves are the right size, or if the tills work.
An app with no data is the same. Every page you build next needs requests, jobs and people to show.
So before any feature, you fill the shelves with sample stock.
Key words
| Word | What it means | Example |
|---|---|---|
| Database | An organised store of data, kept in tables. | |
| Model | A Python class that stands for one table. | class Ticket |
| Primary key | A field that is different for every row. | id |
| Foreign key | A field that points at a row in another table. | company_id |
| Hashing | Scrambling data one way, so it cannot be turned back. | |
| Sample data | Made-up records for building and checking an app. |
The cells students fill in are left blank in this preview.
By the end of this lesson
Note
I can turn a data design into Flask-SQLAlchemy models.
Starter: what you already know
Have a go
Starter: what you already know
3 questionsSprint 0, step 3: the goal
| Part | For this step |
|---|---|
| Sprint (a short block of work) | Sprint 0: a project that runs, a page layout and sample data. |
| This step | The six tables from the Task 1 data design, and a script that fills them. |
| Stories | None directly. Every story from E1 to E5 reads or writes these tables. |
The cells students fill in are left blank in this preview.
One class for each table
Flask-SQLAlchemy lets you write each table as a Python class, called a model. Each line in the class is a column.
The six models match the Task 1 design: Company, User, Ticket, TicketUpdate, Job and Article.
ForeignKey("company.id") links a ticket to its company. relationship() lets you write ticket.company.name instead of looking it up by hand. The database is SQLite, so it is one file.
Step 3: the Ticket model
# helpdesk/models.py (part)
ROLES = ["customer", "tier1", "tier2", "tier3", "manager"]
PRIORITIES = ["low", "medium", "high", "critical"]
STATUSES = ["new", "open", "waiting", "resolved", "closed"]
class Ticket(db.Model):
"""A support request."""
id: Mapped[int] = mapped_column(primary_key=True)
reference: Mapped[str | None] = mapped_column(String(12), unique=True)
title: Mapped[str] = mapped_column(String(150))
priority: Mapped[str] = mapped_column(String(10))
status: Mapped[str] = mapped_column(String(10), default="new")
company_id: Mapped[int] = mapped_column(ForeignKey("company.id"))
assigned_to_id: Mapped[int | None] = mapped_column(ForeignKey("user.id"))
tier: Mapped[int] = mapped_column(default=1)
created_at: Mapped[datetime] = mapped_column(default=datetime.now)
resolved_at: Mapped[datetime | None]
company: Mapped["Company"] = relationship()
def set_reference(self):
self.reference = f"NTH-{self.id:04d}"
Make a free account to save your work and track your progress.
Check: models and keys
Have a go
Check: models and keys
3 questionsAllowed values are written once
At the top of models.py are lists such as PRIORITIES and STATUSES. These are constants: values that never change while the app runs. Python writes them in capitals.
Every form and every check uses these lists. So a ticket can never get a priority that is not on the list.
The reference, such as NTH-0007, is made from the ticket's id by set_reference().
Try it: make a reference
# The reference is made from the ticket's id.
# :04d means "a whole number, at least 4 digits, with 0s in front".
for ticket_id in [1, 7, 42, 1234]:
reference = f"NTH-{ticket_id:04d}"
print(ticket_id, "becomes", reference)
# Change 04d to 06d, then press Run. What changes?
Make a free account to save your work and track your progress.
Passwords are hashed, never stored
The User model never keeps a password. It keeps a hash, made by Werkzeug, which comes with Flask.
A hash cannot be turned back into the password. To sign in, the app hashes what you typed and compares the two.
A random salt (extra random letters) is added first. Two people with the same password still get different hashes.
Step 3: hashing on the User model
# helpdesk/models.py, inside class User (part)
# Only a one-way hash of the password is kept, never the password itself.
password_hash: Mapped[str] = mapped_column(String(256))
def set_password(self, password):
# generate_password_hash adds a random salt, so two users with the
# same password still get different hashes.
hashed = generate_password_hash(password)
self.password_hash = hashed
def check_password(self, password):
return check_password_hash(self.password_hash, password)
Make a free account to save your work and track your progress.
Check: constants and passwords
Have a go
Check: constants and passwords
3 questionsA script fills the tables
seed.py deletes everything, makes the tables again and adds sample data: four companies, ten people, twenty requests, jobs and articles.
Every date is worked out from today, so the data always looks recent.
The phone numbers come from a range set aside for TV drama, so no real business is rung. Every demo account shares one easy password, marked as demo only.
Step 3: part of seed.py
# seed.py (part)
# DEMO ONLY: every sample account signs in with this same easy password.
EVERYONE_SIGNS_IN_WITH = "password123"
app = create_app()
with app.app_context():
db.drop_all() # WARNING: deletes everything first
db.create_all()
# ... add the companies, users and tickets ...
# flush() sends the new rows to the database so they get their ids,
# which the references are made from.
db.session.flush()
for ticket in tickets:
ticket.set_reference()
# Set updated_at here, after the reference: otherwise saving the
# reference would stamp updated_at with the time right now.
ticket.updated_at = ticket.resolved_at or ticket.created_at
Make a free account to save your work and track your progress.
A common mistake
Warning
Many students think code from an AI coding assistant is right if it runs. The first draft of this script ran. But saving each reference also stamped updated_at with the time right now, so every request looked just changed. Look at the data your code makes, not only whether it crashes.
Match each model to what it holds
Have a go
Loading…
Your answers are marked here and are not kept. A college account keeps every student’s marks.
Build it yourself: step 3
Build step 3. 1. Make extensions.py with the db object. 2. Write models.py with your six models from the Task 1 data design, the allowed values as constants, and set_password and check_password on User. 3. In create_app, set the database address, call db.init_app and db.create_all. 4. Write seed.py with at least three companies, one user of each role and ten requests. 5. Run it, then open the database in a viewer or print counts on the home page. 6. Write the change log row. Note any column you changed from your Task 1 design, and why.
A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.
Make a free account to save your work, or press Start lab to work through the whole lesson.
Compare with the step 3 code
Tip
Compare yours with the step 3 code on GitHub. Check each column against your Task 1 data design. Where you changed the design, say why in the change log.
Change log entry for step 3
| Date | Version and files | What changed | Why |
|---|---|---|---|
| 4 March | step-03: extensions.py, models.py, seed.py, __init__.py | Six models from the data design, allowed values as constants, password hashing, a sample data script | Every feature needs data, and sample data shows pages working early |
The cells students fill in are left blank in this preview.
Next: Sprint 1 begins with sign in
Sprint 0 is done: the app runs, has a layout and has data. Sprint 1 is about support requests. It starts in step 4 with signing in, because almost every page depends on who you are.
Exit quiz
Have a go