Add .env-example file and update configuration for environment variables

- Created .env-example for environment variable setup
- Updated README to reflect changes in .env file creation
- Modified config.py to include new environment variables and DATABASE_URL property
- Enhanced database.py with connect and disconnect functions
- Updated main.py to manage database connection lifecycle
- Adjusted compose.yaml for consistent environment variable usage
This commit is contained in:
2026-02-24 13:38:54 +01:00
parent a5c93d1f8a
commit 17d3b1caac
6 changed files with 60 additions and 28 deletions

View File

@ -1,6 +1,23 @@
from pydantic_settings import BaseSettings
from pydantic import computed_field
class Settings(BaseSettings):
DATABASE_URL: str = "${DATABASE_URL}"
POSTGRES_USER: str
POSTGRES_PASSWORD: str
POSTGRES_DB: str
API_PORT: int = 8000
DEBUG: bool = False
@computed_field
@property
def DATABASE_URL(self) -> str:
return (
f"postgresql+asyncpg://"
f"{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}"
f"@db/{self.POSTGRES_DB}"
)
class Config:
env_file = ".env"
settings = Settings()

View File

@ -1,11 +1,22 @@
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
from sqlalchemy import text
from app.config import settings
engine = create_async_engine(settings.DATABASE_URL, echo=True)
engine = create_async_engine(settings.DATABASE_URL, echo=settings.DEBUG)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async def connect():
pass # engine initializes at module level
async def disconnect():
await engine.dispose()
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
yield session
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise

View File

@ -1,14 +1,15 @@
from contextlib import asynccontextmanager
from fastapi import FastAPI
from app.database import engine
from app.database import connect, disconnect
from app.routers import authors, books
@asynccontextmanager
async def lifespan(app: FastAPI):
yield # tables already created by Create.sql
await engine.dispose()
await connect()
yield
await disconnect()
app = FastAPI(title="Database API", lifespan=lifespan)
app.include_router(authors.router)
app.include_router(books.router)
for router in [authors.router, books.router]:
app.include_router(router)