diff --git a/backend/project/__init__.py b/backend/project/__init__.py index 3b0c137b..ec71b0f8 100644 --- a/backend/project/__init__.py +++ b/backend/project/__init__.py @@ -2,11 +2,8 @@ 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 sqlalchemy import URL from flask import Flask -from .database import db +from .database import db, get_database_uri from .endpoints.index.index import index_bp from .endpoints.submissions import submissions_bp @@ -20,7 +17,6 @@ def create_app(): app = Flask(__name__) app.register_blueprint(index_bp) app.register_blueprint(submissions_bp) - return app def create_app_with_db(db_uri: str = None): @@ -35,15 +31,7 @@ def create_app_with_db(db_uri: str = None): #$ flask --app project:create_app_with_db run if db_uri is None: - load_dotenv() - db_uri = URL.create( - drivername=getenv("DB_DRIVER"), - username=getenv("DB_USER"), - password=getenv("DB_PASSWORD"), - host=getenv("DB_HOST"), - port=int(getenv("DB_PORT")), - database=getenv("DB_NAME") - ) + db_uri = get_database_uri() app = create_app() app.config["SQLALCHEMY_DATABASE_URI"] = db_uri diff --git a/backend/project/__main__.py b/backend/project/__main__.py index 22c2a22e..8945aa1f 100644 --- a/backend/project/__main__.py +++ b/backend/project/__main__.py @@ -1,23 +1,11 @@ """Main entry point for the application.""" + from sys import path -from os import getenv -from dotenv import load_dotenv -from sqlalchemy import URL from project import create_app_with_db +from project.database import get_database_uri path.append(".") if __name__ == "__main__": - load_dotenv() - - url = URL.create( - drivername=getenv("DB_DRIVER"), - username=getenv("DB_USER"), - password=getenv("DB_PASSWORD"), - host=getenv("DB_HOST"), - port=int(getenv("DB_PORT")), - database=getenv("DB_NAME") - ) - - app = create_app_with_db(url) + app = create_app_with_db(get_database_uri()) app.run(debug=True) diff --git a/backend/project/database.py b/backend/project/database.py index b62b38c9..1c879be5 100644 --- a/backend/project/database.py +++ b/backend/project/database.py @@ -1,5 +1,25 @@ """Database file""" +from os import getenv from flask_sqlalchemy import SQLAlchemy +from dotenv import load_dotenv +from sqlalchemy import URL db = SQLAlchemy() + +def get_database_uri() -> str: + """Get the database URI made from environment variables + + Returns: + str: Database URI + """ + load_dotenv() + uri = URL.create( + drivername=getenv("DB_DRIVER"), + username=getenv("DB_USER"), + password=getenv("DB_PASSWORD"), + host=getenv("DB_HOST"), + port=int(getenv("DB_PORT")), + database=getenv("DB_NAME") + ) + return uri