diff --git a/.env.template b/.env.template index 57a6357..4fc2e43 100644 --- a/.env.template +++ b/.env.template @@ -3,7 +3,7 @@ SECRET_KEY= SECURITY_PASSWORD_SALT= # Database -SQLALCHEMY_DATABASE_URI=sqlite:///../db/advLab.db +RELATIVE_DB_DIR=db # Server URL SERVER_NAME= diff --git a/advlabdb/__init__.py b/advlabdb/__init__.py index e8832fc..b95e392 100644 --- a/advlabdb/__init__.py +++ b/advlabdb/__init__.py @@ -1,4 +1,4 @@ -from os import environ +from os import environ, makedirs from flask import Flask from flask_admin import Admin @@ -28,7 +28,9 @@ set_from_env(app, "SERVER_NAME") set_from_env(app, "SECRET_KEY") set_from_env(app, "SECURITY_PASSWORD_SALT") -set_from_env(app, "SQLALCHEMY_DATABASE_URI") +app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:///../{environ['RELATIVE_DB_DIR']}/advlab.db" +makedirs(environ["RELATIVE_DB_DIR"], exist_ok=True) + app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["FLASK_ADMIN_FLUID_LAYOUT"] = True diff --git a/advlabdb/database_import.py b/advlabdb/database_import.py index 72a8eee..14ea40d 100644 --- a/advlabdb/database_import.py +++ b/advlabdb/database_import.py @@ -1,4 +1,6 @@ from datetime import datetime +from os import environ +from pathlib import Path from shutil import copy2 from flask import flash, has_request_context @@ -20,6 +22,16 @@ from advlabdb.models import ( User, ) +relative_db_dir = Path(environ["RELATIVE_DB_DIR"]) +relative_db_path = relative_db_dir / "adblab.db" + +relative_db_bk_dir = relative_db_dir / "backups" +relative_db_bk_dir.mkdir(exist_ok=True) + + +def now(): + return datetime.now().strftime("%d_%m_%Y_%H_%M_%S") + def importFromFile(filePath): if filePath[-4:] != ".txt": @@ -259,18 +271,15 @@ def importFromFile(filePath): db.session.add(dbAppointment) # Backup - # TODO: Check existing dirs - src = "db/advLab.db" - dest = f"db/backups/before_{dbSemester.repr()}_import_{datetime.now().strftime('%d_%m_%Y_%H_%M_%S')}.db" - copy2(src, dest) + dest = relative_db_bk_dir / f"before_{dbSemester.repr()}_import_{now()}.db" + copy2(relative_db_path, dest) show(f"Made a backup of the database before the import at {dest}") # Auto commit from the transaction context - src = "db/advLab.db" - dest = f"db/backups/after_{dbSemester.repr()}_import_{datetime.now().strftime('%d_%m_%Y_%H_%M_%S')}.db" - copy2(src, dest) + dest = relative_db_bk_dir / f"after_{dbSemester.repr()}_import_{now()}.db" + copy2(relative_db_path, dest) show(f"Made a backup of the database after the import at {dest}") diff --git a/testDB.py b/testDB.py index 06cccc4..e45bce4 100644 --- a/testDB.py +++ b/testDB.py @@ -1,13 +1,10 @@ from datetime import date -from os import makedirs from flask_security import hash_password from advlabdb import app, db, user_datastore from advlabdb.models import * -makedirs("db", exist_ok=True) - with app.app_context(): db.drop_all() db.create_all()