Download fastapi-backend/app/database.py from APIMoral/README: direct link, hf CLI and curl.
- Browser
- Download file 1.02 kB
-
https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/database.py
- Command line
-
hf download hf://spaces/APIMoral/README/fastapi-backend/app/database.py
-
curl -L -o database.py https://huggingface.co/spaces/APIMoral/README/resolve/main/fastapi-backend/app/database.py
1.02 kB
| from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker | |
| from sqlalchemy.orm import declarative_base | |
| from app.config import settings | |
| import os | |
| # Use SQLite for local testing without Docker | |
| if settings.USE_SQLITE.lower() == "true": | |
| # SQLite file path relative to the backend directory | |
| BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| SQLITE_DB_PATH = os.path.join(BASE_DIR, "chatbot.db") | |
| DATABASE_URL = f"sqlite+aiosqlite:///{SQLITE_DB_PATH}" | |
| else: | |
| DATABASE_URL = settings.DATABASE_URL | |
| engine = create_async_engine(DATABASE_URL, echo=settings.DEBUG) | |
| AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) | |
| Base = declarative_base() | |
| async def get_db(): | |
| async with AsyncSessionLocal() as session: | |
| try: | |
| yield session | |
| await session.commit() | |
| except Exception: | |
| await session.rollback() | |
| raise | |
| finally: | |
| await session.close() | |