database.py
1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import create_engine, event
import os
from pathlib import Path
from dotenv import load_dotenv
# 加载 .env 文件(backend 根目录)
_env_path = Path(__file__).resolve().parent.parent.parent / ".env"
load_dotenv(_env_path)
def _build_database_url() -> str:
"""构建数据库连接 URL。优先 DB_* 环境变量(MySQL),否则用 DATABASE_URL。"""
db_host = os.getenv("DB_HOST")
if db_host:
db_port = os.getenv("DB_PORT", "3306")
db_name = os.getenv("DB_NAME", "")
db_user = os.getenv("DB_USER", "")
db_password = os.getenv("DB_PASSWORD", "")
return f"mysql+pymysql://{db_user}:{db_password}@{db_host}:{db_port}/{db_name}?charset=utf8mb4"
return os.getenv("DATABASE_URL", "sqlite:///./dev.db")
# 数据库连接配置
SQLALCHEMY_DATABASE_URL = _build_database_url()
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args=(
{
"check_same_thread": False,
"timeout": 30,
}
if SQLALCHEMY_DATABASE_URL.startswith("sqlite")
else {}
),
pool_pre_ping=True,
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
if SQLALCHEMY_DATABASE_URL.startswith("sqlite"):
@event.listens_for(engine, "connect")
def set_sqlite_pragma(dbapi_connection, _connection_record):
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA journal_mode=WAL;")
cursor.execute("PRAGMA busy_timeout=30000;")
cursor.execute("PRAGMA synchronous=NORMAL;")
cursor.close()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()