The User Model
Create auth.py with a User model that stores email and hashed password
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Users need a database table
Your expense tracker stores expenses in a database table. User accounts need the same treatment. Each user has three fields:
- id: an auto-assigned integer, same pattern as
Expense - email: the user's login identifier — must be unique so two users cannot register with the same address
- password_hash: the hashed version of the user's password — you never store plain text passwords
The email field uses unique=True to prevent duplicate registrations. It also uses index=True so the database can find a user by email quickly during login, without scanning every row.
This chapter creates a new file called auth.py. It starts small — just the model — and grows across the next three chapters.
Instructions
Create auth.py with the User model.
- Define a class called
Userthat extendsSQLModelwithtable=True— this creates a database table calleduser, just likeExpensecreates anexpensetable. - Add an
idfield:id: Optional[int] = Field(default=None, primary_key=True)— the database assigns this automatically when a new user is created. - Add an
emailfield:email: str = Field(unique=True, index=True)—unique=Trueprevents two users from registering with the same email, andindex=Truemakes login lookups fast. - Add a
password_hashfield as a plainstrwith no constraints. This stores the hashed version of the password, never the original.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding