first commit
This commit is contained in:
56
app/core/database.py
Normal file
56
app/core/database.py
Normal file
@ -0,0 +1,56 @@
|
||||
"""
|
||||
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
|
||||
Reference in New Issue
Block a user