From 21d90e6cd8dac20b01b5d08045ab8b244425f580 Mon Sep 17 00:00:00 2001 From: Kumi Date: Sat, 22 Jun 2024 19:02:50 +0200 Subject: [PATCH] feat(settings): add dynamic DB selection based on config Updated settings to dynamically select the database backend (MySQL, MariaDB, PostgreSQL, or SQLite) based on the configuration file. This change improves flexibility and allows easier customization of the database setup by just modifying the config file. --- freedoi/settings.py | 41 +++++++++++++++++++++++++++++++++-------- 1 file changed, 33 insertions(+), 8 deletions(-) diff --git a/freedoi/settings.py b/freedoi/settings.py index 68acd40..cf259d9 100644 --- a/freedoi/settings.py +++ b/freedoi/settings.py @@ -5,10 +5,10 @@ from autosecretkey import AutoSecretKey # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent -ask = AutoSecretKey("settings.ini", template=BASE_DIR / "settings.ini.template") +ASK = AutoSecretKey("settings.ini", template=BASE_DIR / "settings.ini.template") -SECRET_KEY = ask.secret_key -CONFIG = ask.config +SECRET_KEY = ASK.secret_key +CONFIG = ASK.config DEBUG = CONFIG.getboolean("FreeDOI", "debug", fallback=False) ALLOWED_HOSTS = CONFIG.get("FreeDOI", "host", fallback="*").split(",") @@ -69,12 +69,37 @@ WSGI_APPLICATION = "freedoi.wsgi.application" # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases -DATABASES = { - "default": { - "ENGINE": "django.db.backends.sqlite3", - "NAME": "db.sqlite3", +if (dbtype := "MySQL") in ASK.config or (dbtype := "MariaDB") in ASK.config: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.mysql", + "NAME": ASK.config.get(dbtype, "Database"), + "USER": ASK.config.get(dbtype, "Username"), + "PASSWORD": ASK.config.get(dbtype, "Password"), + "HOST": ASK.config.get(dbtype, "Host", fallback="localhost"), + "PORT": ASK.config.getint(dbtype, "Port", fallback=3306), + } + } + +elif (dbtype := "Postgres") in ASK.config or (dbtype := "PostgreSQL") in ASK.config: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": ASK.config.get(dbtype, "Database"), + "USER": ASK.config.get(dbtype, "Username"), + "PASSWORD": ASK.config.get(dbtype, "Password"), + "HOST": ASK.config.get(dbtype, "Host", fallback="localhost"), + "PORT": ASK.config.getint(dbtype, "Port", fallback=5432), + } + } + +else: + DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": "db.sqlite3", + } } -} # Password validation