config_loader.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import json
  2. from flask_cors import CORS
  3. import os
  4. import logging
  5. from engine.basic_queries import basicQueries
  6. def config(flask_app):
  7. # Get environment label, define conf file name
  8. env_label = os.environ.get('APP_ENVIRONMENT')
  9. if env_label is not None and env_label!="":
  10. confFileName = "config_" + env_label + ".json"
  11. # Default
  12. else:
  13. confFileName = "basic_config.json"
  14. # Read configuration file
  15. confFileName = os.path.join(os.path.dirname(os.path.abspath(__file__)), confFileName)
  16. flask_app.config.from_file(confFileName, load=json.load)
  17. doCommonConfig(flask_app)
  18. # Local environment
  19. if flask_app.config['LOCAL_ENVIRONMENT']:
  20. # This will enable CORS for all routes
  21. CORS(flask_app)
  22. # CORS enabling is useful to prevent annoying CORS error when developing locally
  23. def doCommonConfig(flask_app):
  24. # Config DB access
  25. try:
  26. dataConfigObject = flask_app.config['DATA_CONFIG']
  27. dbPath = dataConfigObject['dbPath']
  28. flask_app.config['DATA_CONFIG']['dbPath'] = os.path.join(flask_app.root_path, os.pardir, dbPath)
  29. if dataConfigObject['dynamic_occ_tables']:
  30. # Find the list of occurrences tables dynamically
  31. flask_app.config['DATA_CONFIG']['listOcc'] = get_occ_tables(flask_app.config['DATA_CONFIG'])
  32. else:
  33. if dataConfigObject.get('listOcc') is None:
  34. raise Exception
  35. except:
  36. raise Exception('Error in initializing data configuration')
  37. # Config logging
  38. if flask_app.config['LOGGER_CONFIG'].get('level')=='info':
  39. logging_level = logging.INFO
  40. else:
  41. logging_level = logging.DEBUG
  42. logging.basicConfig(filename = flask_app.config['LOGGER_CONFIG']['filename'],
  43. filemode = 'w',
  44. format = '%(asctime)s %(message)s',
  45. level=logging_level)
  46. def get_occ_tables(dataConfig):
  47. handler = basicQueries(dataConfig)
  48. all_tables = handler.queryHandler.query({'queryType': 'occ_tables'})
  49. occ_tables = [table['name'] for table in all_tables if table['name'].startswith('Occ')]
  50. return occ_tables