Skip to content
Snippets Groups Projects
__init__.py 1.97 KiB
"""
Creates the application.
"""
import os
import logging
from flask import Flask
from flask_cors import CORS
from dotenv import load_dotenv
from pony.orm import Database, db_session, count
from pony.orm.dbapiprovider import OperationalError
from pony.orm.core import ERDiagramError, TransactionIntegrityError
from time import sleep


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
load_dotenv()

app = Flask(__name__)
app.dotenv = os.environ

app.config["DATA_DIR"] = "/storage/app/data"
app.config["ASSETS_DIR"] = "/storage/app/assets"
app.config.update(SECRET_KEY=os.environ["FLASK_SECRET_KEY"])
app.dotenv = os.environ
app.config["PONY"] = {
    "provider": "postgres",
    "user": os.environ["PG_USER"],
    "password": os.environ["PG_PASSWORD"],
    "host": os.environ["PG_HOST"],
    "port": os.environ["PG_PORT"],
    "database": os.environ["PG_DB"],
}

with app.app_context():
    # connect to db
    db = Database()
    connected = False
    count = 0
    while not connected:
        try:
            db.bind(**app.config["PONY"])
            connected = True
        except OperationalError as er:
            if count > 10:
                logger.error("error connecting to database 10 times\n%s", er)
                quit(-1)
            count += 1
            sleep(5)

    from app.entities import Network, Simulation, City, Status, Plan

    db.generate_mapping(check_tables=True, create_tables=False)

with app.app_context():
    # register apis
    from app.api.network_operations import network_operations
    from app.api.kpis import kpis
    from app.api.dexi import dss
    from app.api.geojsons import geojsons
    from app.api.calibration_preprocess import calibration_preprocess
    from app.api.pt_fleet import pt_fleet

    app.register_blueprint(network_operations)
    app.register_blueprint(kpis)
    app.register_blueprint(geojsons)
    app.register_blueprint(dss)
    app.register_blueprint(calibration_preprocess)
    app.register_blueprint(pt_fleet)

CORS(app)