chore: initialize server repository
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def configured_path(name: str, default: str) -> Path:
|
||||
path = Path(os.getenv(name, default)).expanduser()
|
||||
return path if path.is_absolute() else BASE_DIR / path
|
||||
|
||||
|
||||
DB_FILE = configured_path("DB_FILE", "mini.db")
|
||||
SQL_FILE = configured_path("SQL_FILE", "tables.sql")
|
||||
|
||||
# 初始化数据库
|
||||
def init_db():
|
||||
conn = sqlite3.connect(DB_FILE, timeout=30, check_same_thread=False)
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
cur = conn.cursor()
|
||||
sql = Path(SQL_FILE).read_text("utf-8")
|
||||
cur.executescript(sql)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
print(f"数据库 {DB_FILE} 创建完成")
|
||||
|
||||
# 获取连接
|
||||
def get_conn():
|
||||
conn = sqlite3.connect(DB_FILE, timeout=30, check_same_thread=False)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA foreign_keys=ON")
|
||||
return conn
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db()
|
||||
Reference in New Issue
Block a user