57 lines
1.2 KiB
Python
57 lines
1.2 KiB
Python
"""
|
|
Database Configuration and Session Management
|
|
|
|
Provides database initialization, session management, and base models
|
|
following the Python Quick Start Guide best practices.
|
|
"""
|
|
|
|
from flask_sqlalchemy import SQLAlchemy
|
|
from typing import Generator
|
|
from sqlalchemy.orm import Session
|
|
|
|
# Database instance
|
|
db = SQLAlchemy()
|
|
|
|
|
|
def init_db(app) -> None:
|
|
"""
|
|
Initialize database with Flask app.
|
|
|
|
Args:
|
|
app: Flask application instance
|
|
"""
|
|
db.init_app(app)
|
|
|
|
|
|
def get_db_session() -> Session:
|
|
"""
|
|
Get current database session.
|
|
|
|
Returns:
|
|
SQLAlchemy session instance
|
|
|
|
Note:
|
|
This is a Flask-SQLAlchemy session, managed automatically.
|
|
Use db.session throughout the application.
|
|
"""
|
|
return db.session
|
|
|
|
|
|
# For FastAPI-style dependency injection (if migrating to FastAPI later)
|
|
def get_db() -> Generator[Session, None, None]:
|
|
"""
|
|
Get database session for dependency injection.
|
|
|
|
Yields:
|
|
Database session
|
|
|
|
Usage:
|
|
def some_function(db: Session = Depends(get_db)):
|
|
# Use db session
|
|
"""
|
|
try:
|
|
yield db.session
|
|
finally:
|
|
# Flask-SQLAlchemy handles cleanup automatically
|
|
pass
|