# Path: drift/flaskfactory.py
# def load_flask_config(app_root=None):
#     if _sticky_app_config is not None:
#         return _sticky_app_config
# 
#     app_root = app_root or get_app_root()
#     config_filename = os.path.join(app_root, 'config', 'config.json')
#     if not os.path.exists(config_filename):
#         raise AppRootNotFound("No config file found at: '{}'".format(config_filename))
# 
#     log.info("Loading configuration from %s", config_filename)
#     with open(config_filename) as f:
#         config_values = json.load(f)
# 
#     config_values['app_root'] = app_root
#     return config_values
# 
# Path: drift/core/extensions/driftconfig.py
# def check_tenant(f):
#     """Make sure current tenant is provided, provisioned and active."""
#     @wraps(f)
#     def _check(*args, **kwargs):
#         if not tenant_from_hostname:
#             abort(
#                 http_client.BAD_REQUEST,
#                 description="No tenant specified. Please specify one using host name prefix or "
#                 "the environment variable DRIFT_DEFAULT_TENANT."
#             )
# 
#         conf = current_app.extensions['driftconfig'].get_config()
#         if not conf.tenant:
#             # This will trigger a proper exception
#             try:
#                 get_config_for_request(allow_missing_tenant=False)
#                 raise RuntimeError("Should not reach this.")
#             except TenantNotConfigured as e:
#                 abort(http_client.BAD_REQUEST, description=str(e))
# 
#         check_tenant_state(g.conf.tenant)
#         return f(*args, **kwargs)
# 
#     return _check


import os
import os.path
import importlib
import socket
import getpass
import time
import logging
from contextlib import contextmanager
from six.moves import http_client
from click import echo
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from werkzeug.local import LocalProxy
from sqlalchemy import create_engine
from flask import g, abort
from flask import _app_ctx_stack as stack, current_app
from flask_sqlalchemy import SQLAlchemy
from drift.flaskfactory import load_flask_config
from drift.core.extensions.driftconfig import check_tenant
    from alembic.config import Config
    from alembic import command
    from drift.utils import get_app_root

    @classmethod
    def get_application_name(cls):

        if cls.application_name is None:
            # Pretty print a nice name for this connection, just in time.
            cls.application_name = '{}:{}@{}'.format(
                load_flask_config()['name'],
                getpass.getuser(),
                socket.gethostname().split(".")[0],
            )

        return cls.application_name


def drift_init_extension(app, **kwargs):
    Postgres(app)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'  # Just to quiet down a warning
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # https://tinyurl.com/SQLALCHEMY-TRACK-MODIFICATIONS
    app.config.setdefault('SQLALCHEMY_ENGINE_OPTIONS', {}).update({
        'connect_args': {
            'connect_timeout': 10,
            'application_name': Postgres.get_application_name(),
        },
        'pool_pre_ping': True
    })
    SQLAlchemy(app)



# Path: drift/flaskfactory.py
# def load_flask_config(app_root=None):
#     if _sticky_app_config is not None:
#         return _sticky_app_config
# 
#     app_root = app_root or get_app_root()
#     config_filename = os.path.join(app_root, 'config', 'config.json')
#     if not os.path.exists(config_filename):
#         raise AppRootNotFound("No config file found at: '{}'".format(config_filename))
# 
#     log.info("Loading configuration from %s", config_filename)
#     with open(config_filename) as f:
#         config_values = json.load(f)
# 
#     config_values['app_root'] = app_root
#     return config_values
# 
# Path: drift/core/extensions/driftconfig.py
# def check_tenant(f):
#     """Make sure current tenant is provided, provisioned and active."""
#     @wraps(f)
#     def _check(*args, **kwargs):
#         if not tenant_from_hostname:
#             abort(
#                 http_client.BAD_REQUEST,
#                 description="No tenant specified. Please specify one using host name prefix or "
#                 "the environment variable DRIFT_DEFAULT_TENANT."
#             )
# 
#         conf = current_app.extensions['driftconfig'].get_config()
#         if not conf.tenant:
#             # This will trigger a proper exception
#             try:
#                 get_config_for_request(allow_missing_tenant=False)
#                 raise RuntimeError("Should not reach this.")
#             except TenantNotConfigured as e:
#                 abort(http_client.BAD_REQUEST, description=str(e))
# 
#         check_tenant_state(g.conf.tenant)
#         return f(*args, **kwargs)
# 
#     return _check


# Path: drift/core/resources/postgres.py
import os
import os.path
import importlib
import socket
import getpass
import time
import logging
from contextlib import contextmanager
from six.moves import http_client
from click import echo
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import NullPool
from werkzeug.local import LocalProxy
from sqlalchemy import create_engine
from flask import g, abort
from flask import _app_ctx_stack as stack, current_app
from flask_sqlalchemy import SQLAlchemy
from drift.flaskfactory import load_flask_config
from drift.core.extensions.driftconfig import check_tenant
    from alembic.config import Config
    from alembic import command
    from drift.utils import get_app_root


    @classmethod
    def get_application_name(cls):

        if cls.application_name is None:
            # Pretty print a nice name for this connection, just in time.
            cls.application_name = '{}:{}@{}'.format(
                load_flask_config()['name'],
                getpass.getuser(),
                socket.gethostname().split(".")[0],
            )

        return cls.application_name


def drift_init_extension(app, **kwargs):
    Postgres(app)

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'  # Just to quiet down a warning
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # https://tinyurl.com/SQLALCHEMY-TRACK-MODIFICATIONS
    app.config.setdefault('SQLALCHEMY_ENGINE_OPTIONS', {}).update({
        'connect_args': {
            'connect_timeout': 10,
            'application_name': Postgres.get_application_name(),
        },
        'pool_pre_ping': True
    })
    SQLAlchemy(app)



@check_tenant