From 25c5a4179ca6c633fc8d236d4cc8264a821497ed Mon Sep 17 00:00:00 2001 From: Benjamin Sigonneau Date: Wed, 20 Jul 2022 23:31:12 +0200 Subject: [PATCH] Database: allow mysql, config in ini file Also check for ini file existence at startup --- .gitignore | 1 + config.py | 8 +++++++- fioul.ini.example | 13 +++++++++++++ models.py | 17 +++++++++++++++-- 4 files changed, 36 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index aa28b5b..5412005 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.db +fioul.ini __pycache__ diff --git a/config.py b/config.py index c874a67..cce3d3f 100644 --- a/config.py +++ b/config.py @@ -2,4 +2,10 @@ from configparser import ConfigParser import os conf = ConfigParser() -conf.read(os.path.dirname(__file__) + "/fioul.ini") +ini_file = os.path.dirname(__file__) + "/fioul.ini" +try: + conf.read_file(open(ini_file)) +except FileNotFoundError: + print("Configuration file 'fioul.ini' not found") + print("Please take a look at 'fioul.ini.example' to create one") + exit(42) diff --git a/fioul.ini.example b/fioul.ini.example index 9f13c5e..97937f8 100644 --- a/fioul.ini.example +++ b/fioul.ini.example @@ -1,3 +1,16 @@ +[db] +backend = sqlite + +[sqlite] +filename = fioul.db + +[mysql] +database = fioul +user = please change me +password = please change me +host = localhost +port = 3306 + [server] host = localhost port = 9980 diff --git a/models.py b/models.py index 48b9cd6..63e861f 100644 --- a/models.py +++ b/models.py @@ -1,11 +1,24 @@ +from config import conf from peewee import SqliteDatabase from peewee import Model from peewee import AutoField, DateField, IntegerField from peewee import IntegrityError -# SQLite database -db = SqliteDatabase("fioul.db") +backend = conf["db"].get("backend", None) +if backend == "sqlite": + # SQLite database + db = SqliteDatabase(conf["sqlite"].get("filename", "sqlite.db")) +elif backend == "mysql": + db = MySQLDatabase( + conf["mysql"].get("database"), + user=conf["mysql"].get("user"), + password=conf["mysql"].get("password"), + host=conf["mysql"].get("host", "localhost"), + port=conf["mysql"].getint("port", 3306), + ) +else: + db = None class BaseModel(Model):