Files
WGDashboard/src/modules/DatabaseConnection.py

25 lines
974 B
Python
Raw Normal View History

import configparser
import os
from sqlalchemy_utils import database_exists, create_database
2025-09-13 08:23:54 +08:00
def ConnectionString(database) -> str:
parser = configparser.ConfigParser(strict=False)
parser.read_file(open('wg-dashboard.ini', "r+"))
2026-02-07 03:03:35 +01:00
sqlitePath = os.path.join("db")
if not os.path.isdir(sqlitePath):
os.mkdir(sqlitePath)
2026-02-07 03:03:35 +01:00
if parser.get("Database", "type") == "postgresql":
cn = f'postgresql+psycopg://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
2025-06-02 12:04:01 +08:00
elif parser.get("Database", "type") == "mysql":
2025-09-13 08:23:54 +08:00
cn = f'mysql+pymysql://{parser.get("Database", "username")}:{parser.get("Database", "password")}@{parser.get("Database", "host")}/{database}'
else:
cn = f'sqlite:///{os.path.join(sqlitePath, f"{database}.db")}'
2025-06-19 00:41:08 +08:00
try:
if not database_exists(cn):
create_database(cn)
except Exception as e:
exit(1)
2026-02-07 03:03:35 +01:00
return cn