Spaces:
Sleeping
Sleeping
Download app/database.py from Hamza4100/ai-knowledge-assistant: direct link, hf CLI and curl.
- Browser
- Download file 1.04 kB
-
https://huggingface.co/spaces/Hamza4100/ai-knowledge-assistant/resolve/main/app/database.py
- Command line
-
hf download hf://spaces/Hamza4100/ai-knowledge-assistant/app/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Hamza4100/ai-knowledge-assistant/resolve/main/app/database.py
1.04 kB
| """Database configuration and session management.""" | |
| from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker | |
| from sqlalchemy.orm import declarative_base | |
| import os | |
| # Database URL - SQLite for simplicity | |
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./conversations.db") | |
| # Create async engine | |
| engine = create_async_engine( | |
| DATABASE_URL, | |
| echo=False, # Set to True for SQL debugging | |
| future=True, | |
| ) | |
| # Session factory | |
| async_session_maker = async_sessionmaker( | |
| engine, | |
| class_=AsyncSession, | |
| expire_on_commit=False, | |
| ) | |
| # Base class for models | |
| Base = declarative_base() | |
| async def get_db() -> AsyncSession: | |
| """Get database session.""" | |
| async with async_session_maker() as session: | |
| try: | |
| yield session | |
| finally: | |
| await session.close() | |
| async def init_db(): | |
| """Initialize database tables.""" | |
| async with engine.begin() as conn: | |
| await conn.run_sync(Base.metadata.create_all) | |