Created
September 18, 2023 11:35
-
-
Save noor-ul-amin0/937e6a5f81b8da08f4728a20e355b94f to your computer and use it in GitHub Desktop.
FastAPI with SQLAlchemy: This Gist contains a basic setup for using FastAPI with SQLAlchemy. It includes the creation of a database engine, a session local, and a base class for declarative models. It also includes a dependency function for getting the DB session and an annotated DB dependency.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastapi import Depends | |
from sqlalchemy import create_engine | |
from sqlalchemy.orm import sessionmaker, Session | |
from sqlalchemy.ext.declarative import declarative_base | |
from typing import Annotated | |
# Database URL | |
SQLALCHEMY_DATABASE_URL = 'Your database url' | |
# Create engine | |
engine = create_engine(SQLALCHEMY_DATABASE_URL) | |
# Create session local | |
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
# Create base class for declarative models | |
Base = declarative_base() | |
# Dependency for getting DB session | |
def get_db(): | |
db = SessionLocal() | |
try: | |
yield db | |
finally: | |
db.close() | |
# Annotated DB dependency | |
db_dependency = Annotated[Session, Depends(get_db)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add basic SQL db setup in FastAPI