db.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """SQLAlchemy database setup for MySQL.
  2. Reads connection info from environment variables to avoid committing secrets.
  3. - DATABASE_URL: full SQLAlchemy URL (optional)
  4. - DB_USER, DB_PASS, DB_HOST, DB_PORT, DB_NAME: used when DATABASE_URL is not set
  5. Example to set DATABASE_URL locally (Windows PowerShell):
  6. $env:DATABASE_URL = "mysql+pymysql://root:%40%40qinys12346..@192.168.101.7:3306/wishing_tree?charset=utf8mb4&serverTimezone=Asia/Shanghai&use_unicode=true&characterEncoding=utf-8"
  7. Install dependencies: pip install sqlalchemy pymysql
  8. """
  9. import os
  10. from typing import Generator
  11. from sqlalchemy import create_engine
  12. from sqlalchemy.engine import URL
  13. from sqlalchemy.orm import sessionmaker, declarative_base
  14. # Read connection info from environment variables
  15. DATABASE_URL = os.getenv("DATABASE_URL")
  16. DB_USER = os.getenv("DB_USER", "root")
  17. DB_PASS = os.getenv("DB_PASS")
  18. DB_HOST = os.getenv("DB_HOST", "192.168.1.177")
  19. DB_PORT = int(os.getenv("DB_PORT", "3306"))
  20. DB_NAME = os.getenv("DB_NAME", "wishing_tree")
  21. # Extra query params derived from the provided JDBC URL
  22. QUERY = {
  23. "serverTimezone": "Asia/Shanghai",
  24. "useUnicode": "true",
  25. "characterEncoding": "utf-8",
  26. "charset": "utf8mb4",
  27. }
  28. if DATABASE_URL:
  29. # If the user set a full SQLAlchemy URL, prefer it
  30. engine_url = DATABASE_URL
  31. else:
  32. # Build a SQLAlchemy URL object (handles proper quoting)
  33. engine_url = URL.create(
  34. drivername="mysql+pymysql",
  35. username=DB_USER,
  36. password=DB_PASS,
  37. host=DB_HOST,
  38. port=DB_PORT,
  39. database=DB_NAME,
  40. query=QUERY,
  41. )
  42. # Create engine and session factory
  43. # Tune pool parameters as needed for your environment
  44. engine = create_engine(
  45. engine_url,
  46. pool_pre_ping=True,
  47. pool_size=10,
  48. max_overflow=20,
  49. )
  50. SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  51. Base = declarative_base()
  52. # Dependency for FastAPI endpoints
  53. def get_db() -> Generator:
  54. db = SessionLocal()
  55. try:
  56. yield db
  57. finally:
  58. db.close()