Automated Action 1b1f93e10f Create Todo application with FastAPI and SQLite
- Set up project structure with FastAPI
- Create Todo database model and schema
- Implement database connection with SQLAlchemy
- Set up Alembic migrations
- Implement CRUD API endpoints for Todo items
- Add health check endpoint
- Update documentation in README.md

generated with BackendIM... (backend.im)
2025-05-12 05:45:11 +00:00

45 lines
1.2 KiB
Python

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from pathlib import Path
# Create database directory if it doesn't exist
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
# For local development, use a relative path
LOCAL_DB_PATH = Path(__file__).parent.parent.parent / "storage" / "db"
LOCAL_DB_PATH.mkdir(parents=True, exist_ok=True)
LOCAL_DB_URL = f"sqlite:///{LOCAL_DB_PATH}/db.sqlite"
# Choose the appropriate URL based on environment
DATABASE_URL = LOCAL_DB_URL # Default to local development
engine = create_engine(
DATABASE_URL,
connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""
Dependency function to get a database session.
Used as a FastAPI dependency in route handlers.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()
def create_db_and_tables():
"""
Create database tables if they don't exist.
Call this function on application startup.
"""
Base.metadata.create_all(bind=engine)