Explorar o código

Added sexy app config v0

kora %!s(int64=2) %!d(string=hai) anos
pai
achega
ba267ec9c2

+ 0 - 0
flask_be/Config/__init.py__


+ 12 - 0
flask_be/Config/basic_config.json

@@ -0,0 +1,12 @@
+{
+    "DATA_CONFIG": {
+        "dbPath": "db/first_db/",
+        "dbfile_default": "test1.db",
+        "data_interface": "sqlite3",
+        "listOcc": ["occ00001", "occ00002", "occ00003"]
+    },
+    "LOGGER_CONFIG": {
+        "filename": "Progetto2023_BE.log",
+        "level": "info"
+    }
+}

+ 44 - 0
flask_be/Config/config_loader.py

@@ -0,0 +1,44 @@
+import json
+from flask_cors import CORS
+import os
+import logging
+
+
+def config(flask_app):
+
+    env_label = os.environ.get('APP_ENVIRONMENT')
+    
+    # Local development
+    if env_label=='local_development':
+        configLocal(flask_app)
+    
+    # Any different environments needed, including production
+    #elif:
+    #
+
+    # Default
+    else:
+        configLocal(flask_app)
+
+def configLocal(flask_app):
+    # Read configuration file
+    flask_app.config.from_file(os.path.dirname(os.path.abspath(__file__)) + "/basic_config.json", load=json.load)
+    
+    # This will enable CORS for all routes
+    CORS(flask_app) 
+    # CORS enabling is useful to prevent annoying CORS error when developing locally
+
+    # Config DB access
+    try:
+        dbPath = flask_app.config['DATA_CONFIG']['dbPath']
+        flask_app.config['DATA_CONFIG']['dbPath'] = os.path.join(flask_app.root_path, os.pardir, dbPath)
+    except:
+        raise Exception('Missing required configuration variable: dbPath')
+
+    # Config logging
+    if flask_app.config['LOGGER_CONFIG'].get('level')=='info':
+        logging_level = logging.INFO
+    else:
+        logging_level = logging.DEBUG
+    logging.basicConfig(filename = flask_app.config['LOGGER_CONFIG']['filename'], level=logging_level)
+

+ 6 - 28
flask_be/app.py

@@ -1,36 +1,14 @@
-import logging
 from flask import Flask, request
-from flask_cors import CORS
-import json
-import os.path
+import logging
 import traceback
+import os.path
 
 from engine.handle_request import handleOccGetQuery, handleGetContext
+from Config.config_loader import config
 
 
 app = Flask(__name__)
-CORS(app) # This will enable CORS for all routes
-# CORS enabling is useful to prevent annoying CORS error when developing locally
-
-# Configuration for the app, particularly for DB & other possible data provider(s)
-# Eventually should be put in a config file (or similar general solution)
-customAppConfig = {
-    'dataConfig': {
-        'appath': app.root_path,
-        'dbpath': os.path.join(app.root_path, os.pardir) + '/db/first_db/',
-        'dbfile_default': 'test1.db',
-        'data_interface': 'sqlite3',
-        'listOcc': ["occ00001", "occ00002", "occ00003"]
-    },
-    'loggerConfig': {
-        'filename': 'Progetto2023_BE.log',
-        'level': logging.INFO
-    }
-}
-
-logging.basicConfig(filename = customAppConfig['loggerConfig']['filename'], level=customAppConfig['loggerConfig']['level'])
-
-# ADD LOGGING?
+config(app)
 
 
 ################################################################
@@ -49,7 +27,7 @@ def simpleQuery():
         queryDTO = request.get_json() # new (and correct) way!
         queryList = queryDTO['queryList']
         cooccorrenze = queryDTO.get('cooccorrenze')
-        output = handleOccGetQuery(queryList, cooccorrenze, customAppConfig['dataConfig'])
+        output = handleOccGetQuery(queryList, cooccorrenze, app.config['DATA_CONFIG'])
 
 #        for row in output:
 #            print(row)
@@ -76,7 +54,7 @@ def simpleContext():
         listResults = queryDTO['listResults']
         cooccorrenze = queryDTO['cooccorrenze']
 
-        output = handleGetContext(queryList, listResults, cooccorrenze, customAppConfig['dataConfig'])
+        output = handleGetContext(queryList, listResults, cooccorrenze, app.config['dataConfig'])
 
         return output, 200
 

+ 4 - 4
flask_be/data_interface_sqlite3/query_handlers.py

@@ -21,8 +21,8 @@ def simpleQueryHandlerV0(data, path):
 # Actual thing, first version
 class queryHandlerBasicSqlite:
 
-    def __init__(self, dbpath, dbfileDefault):
-        self.dbpath = dbpath
+    def __init__(self, dbPath, dbfileDefault):
+        self.dbPath = dbPath
         self.dbfileDefault = dbfileDefault
     
     def query(self, queryData, pandas=False, dbFile=None):
@@ -35,7 +35,7 @@ class queryHandlerBasicSqlite:
 
         dbfileLocal = dbFile if dbFile is not None else self.dbfileDefault
 
-        db = self.dbpath + dbfileLocal
+        db = self.dbPath + dbfileLocal
         
         connection = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
         # PANDAS?
@@ -58,7 +58,7 @@ class queryHandlerBasicSqlite:
         except:
             return None
 
-        with open(f"{self.dbpath}/itxt/{sigla}", 'r', encoding="utf-32-le") as file1:
+        with open(f"{self.dbPath}/itxt/{sigla}", 'r', encoding="utf-32-le") as file1:
             file1.seek(4*minChar)
             cont = file1.read(maxChar-minChar)
             return cont

+ 2 - 2
flask_be/engine/data_providers_setup.py

@@ -5,9 +5,9 @@ class queryHandlerBasic:
     def __init__(self, dataConfig):
         
         if dataConfig['data_interface']=='sqlite3':
-            dbpath = dataConfig['dbpath']
+            dbPath = dataConfig['dbPath']
             dbfileDefault = dataConfig['dbfile_default']
-            self._queryHandler = queryHandlerBasicSqlite(dbpath, dbfileDefault)
+            self._queryHandler = queryHandlerBasicSqlite(dbPath, dbfileDefault)
         else:
             raise Exception('Unrecognized data interface in app configuration')