FAST API connecting to Data Base Using SQLAlchemy ORM

from collections.abc import AsyncGenerator
import uuid # UUID = Universally Unique Identifier.
from sqlalchemy import Column , String , Text , DateTime , ForeignKey
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.asyncio import AsyncSession , create_async_engine , async_sessionmaker
from sqlalchemy.orm import DeclarativeBase , relationship
import datetime
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
# this will use local data base for practive later on we will use the actual data base like postgresql
class Post(DeclarativeBase):
__tablename__ = "posts"
id = Column(UUID(as_uuid=True) , primary_key=True , default=uuid.uuid4)
# as_uuid=True is Returned as Python UUID object so inside python it will be like type(post.id)(better)
# default=uuid.uuid4 : if no id is provided, automatically generate one..
# uuid.uuid4() generates a random UUID.
caption = Column(Text)
url = Column(String , nullable=False)
file_type = Column(String , nullable=False)
file_name = Column(String , nullable=False)
created_at = Column(DateTime , dafault=datetime.utcnow)
Dont worry i will explain:
class Post(DeclarativeBase):
__tablename__ = "posts"
Notice important snippet here :
class Post(DeclarativeBase):
You are creating a model class
That class represents a database table
In SQLAlchemy ORM:
A class = a table
An object of that class = a row in the table
class Post(DeclarativeBase):
means : Post is a table model that inherits from SQLAlchemy's base class
What is DeclarativeBas ?
In SQLAlchemy 2.0, we define a base like this:
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
This Base is parent of all models…
class Post(Base):
__tablename__ = "posts"
So DeclarativeBase :
Registers the class as a database model
Connects it to SQLAlchemy ORM system
Keeps track of metadata
Without inheriting from it → SQLAlchemy will NOT recognize it as a table.
What is __tablename__ = “posts” :
Means:
Database table name -> posts
NOW :
id = Column(UUID(as_uuid=True) , primary_key=True , default=uuid.uuid4)
i am telling that make a Column named as id that why i wrote id = Column()
Means :
Create a column named id in the database that stores a UUID, make it the primary key, and automatically generate a new UUID when a row is created.
UUID(as_uuid=True)
This defines the data type.
What is UUID?
UUID = Universally Unique Identifier
Example:
550e8400-e29b-41d4-a716-446655440000
primary_key=True :
Primary key:
Must be unique
Cannot be NULL
Identifies each row
So every post will have a unique UUID.
default=uuid.uuid4
This is VERY important.
It means:
"If no id is provided, automatically generate one."
uuid.uuid4() generates a random UUID.
and rest are just so easy :
caption = Column(Text)
# create a column named as caption it will contain Text
url = Column(String , nullable=False)
# url column will contain String and can't be null so user should always put some string
file_type = Column(String , nullable=False)
# same apply here
file_name = Column(String , nullable=False)
# same also
created_at = Column(DateTime , dafault=datetime.utcnow)
# DateTime
DateTime :
This is a SQLAlchemy database column type.
It tells the database:
"Store date and time in this column."
It defines the SQL data type, not a Python value.
datetime :
his is a Python built-in class.
It creates actual date-time values in Python.
Example:
datetime.utcnow()

