From 3e95b1f869d9aa10548bb0b7dba5ff88482ea8a0 Mon Sep 17 00:00:00 2001 From: cmekeirl Date: Wed, 21 Feb 2024 14:48:22 +0100 Subject: [PATCH] db_uri and code clean --- backend/environment.env | 1 + backend/project/__init__.py | 16 ++++++++++------ backend/project/__main__.py | 7 +++++-- 3 files changed, 16 insertions(+), 8 deletions(-) create mode 100644 backend/environment.env diff --git a/backend/environment.env b/backend/environment.env new file mode 100644 index 00000000..fa8d765c --- /dev/null +++ b/backend/environment.env @@ -0,0 +1 @@ +DB_HOST=sqlite:///path/to/your/database.db diff --git a/backend/project/__init__.py b/backend/project/__init__.py index 5e0be62f..e38de8a9 100644 --- a/backend/project/__init__.py +++ b/backend/project/__init__.py @@ -2,23 +2,27 @@ This file is the base of the Flask API. It contains the basic structure of the API. """ -from os import getenv -from dotenv import load_dotenv from flask import Flask from flask_sqlalchemy import SQLAlchemy from .endpoints.index import index_bp +db = SQLAlchemy() + def create_app(): """ Create a Flask application instance. Returns: Flask -- A Flask application instance """ - db = SQLAlchemy() - load_dotenv() + app = Flask(__name__) - app.config['SQLALCHEMY_DATABASE_URI'] = getenv('DB_HOST') app.register_blueprint(index_bp) - db.init_app(app) return app + +def init_db(db_uri): + """Initialize the database with the given uri""" + app = create_app() + app.config["SQLALCHEMY_DATABASE_URI"] = db_uri + db.init_app(app) + return app diff --git a/backend/project/__main__.py b/backend/project/__main__.py index 077da8ea..b573ee8c 100644 --- a/backend/project/__main__.py +++ b/backend/project/__main__.py @@ -1,9 +1,12 @@ """Main entry point for the application.""" from sys import path -from project import create_app +from os import getenv +from project import init_db +from dotenv import load_dotenv path.append(".") if __name__ == "__main__": - app = create_app() + load_dotenv(dotenv_path='environment.env') + app = init_db(getenv("DB_HOST")) app.run(debug=True)