KevsRobots Learning Platform
55% Percent Complete
By Kevin McAleer, 3 Minutes

In building our authentication system, the first step is to create models that define the structure of user data. These models ensure that the data is valid, consistent, and ready for storage in a database. Weβll use Pydantic for data validation and SQLAlchemy for Object-Relational Mapping (ORM) to interact with our database.
Pydantic uses Python type annotations to validate data. This ensures that the data conforms to specified formats before we process it or save it to our database.
Letβs define a simple user model with Pydantic to validate user registration data:
from pydantic import BaseModel, EmailStr
class UserCreate(BaseModel):
username: str
email: EmailStr
password: str
This model will validate that the username is a string, the email is a valid email address, and the password is also a string.
SQLAlchemy is an ORM library that allows us to interact with databases using Python classes and objects. It abstracts away SQL queries, making database operations more Pythonic and secure.
Now, letβs define an SQLAlchemy model for our users:
from sqlalchemy import Column, Integer, String
from .database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
Notice weβre storing hashed_password instead of password. Itβs crucial never to store plain passwords in your database for security reasons.
While Pydantic models are great for input validation and serialization, SQLAlchemy models are used for database operations. In practice, youβll often convert between these two model types.
For example, after validating user registration data with a Pydantic model, youβll convert this data into an SQLAlchemy model before saving it to the database. Similarly, when fetching user data from the database, youβll convert SQLAlchemy models into Pydantic models before sending them to clients.
Youβve learned how to define user models using Pydantic for validation and SQLAlchemy for database interaction. These models form the backbone of our user authentication system, ensuring data integrity and security. In the next lesson, weβll implement user registration and login functionalities using these models.
Try adding additional fields to the UserCreate Pydantic model, such as first_name and last_name, and reflect on how these additions might be validated. Consider the types of validation that would be appropriate for these fields.
You can use the arrows β β on your keyboard to navigate between lessons.
Comments