xiaozhi-esp32-server/web/api/db/database.py
kalicyh c81b6b6527 🦄 refactor: 重写前端
路由守护尚未写完
2025-03-03 09:12:33 +08:00

31 lines
892 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# api/db/database.py
import os
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 获取数据库连接 URL,可通过环境变量设置,例如:
# SQLite: sqlite:///./sql_app.db
# PostgreSQL: postgresql+asyncpg://user:password@localhost/dbname
# MySQL: mysql+pymysql://user:password@localhost/dbname
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./sql_app.db")
if DATABASE_URL.startswith("sqlite"):
engine = create_engine(
DATABASE_URL, connect_args={"check_same_thread": False}
)
else:
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""
获取数据库会话
"""
db = SessionLocal()
try:
yield db
finally:
db.close()