def init_app(app):
    """
    Init flask services and dependencies
    :param app: flask app
    :return:
    """
    app.logger.info(f'Configure app in {APP_ENV} environment')
    app.config.from_object(settings_container.get(APP_ENV))
    flask_api_doc(app,
                  config_path=os.path.abspath(__file__).replace(
                      'flasksrc/app_setup.py', '') + 'swagger.json',
                  url_prefix='/swagger',
                  title='Swagger from Flask Boilerplate')
    cache.init_app(app)
    bcrypt.init_app(app)
    db_init_app(app)
    CORS(app, supports_credentials=True)
    healthcheck_init_app(app)
    register_blueprints(app)
    app.register_error_handler(500, error_handler)

    @app.teardown_appcontext
    def shutdown_db_session(exception=None):
        db.session.remove()

    @app.before_first_request
    def setup():
        db_starter = PopulateInitialData(db_session=db.session)
        db_starter.start_populate()
    def start_populate(self):
        role = self._role_repository.filter_by_name("default")
        if not role:
            role = self._role_model(name="default")
            self._insert_row(role)

        user = self._user_repository.filter_by_email(
            settings_container.get(APP_ENV).FIRST_SUPERUSER)
        if not user:
            user = self._user_model(
                email=settings_container.get(APP_ENV).FIRST_SUPERUSER,
                password=settings_container.get(
                    APP_ENV).FIRST_SUPERUSER_PASSWORD,
                first_name="default_first_name",
                last_name="default_last_name",
                roles=[role],
                is_superuser=True)
            self._insert_row(user)
Beispiel #3
0
def create_token_service():
    token_repository = InvalidTokenRepository(db_session=db.session)
    return TokenService(
        create_token_entity_usecase=CreateTokenEntityUseCase(),
        filter_token_by_token_usecase=FilterTokenByTokenUseCase(
            repository=token_repository),
        invalidate_token_usecase=InvalidateTokenUseCase(
            repository=token_repository),
        get_auth_token=GetAuthTokenUseCase(request=request),
        secret=settings_container.get(APP_ENV).SECRET_KEY)
Beispiel #4
0
import os
import logging

from flask import Flask
from src.frameworks_and_drivers.flasksrc.app_setup import init_app
from src.frameworks_and_drivers.settings import settings_container, APP_ENV

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s]: {} %(levelname)s %(message)s'.format(os.getpid()),
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=[logging.StreamHandler()])
logger = logging.getLogger()


def create_app():
    app = Flask(__name__)
    init_app(app)
    return app


if __name__ == "__main__":
    app = create_app()
    app.run(debug=os.environ.get('DEBUG', False),
            host="0.0.0.0",
            port=settings_container.get(APP_ENV).port)
Beispiel #5
0
        def make_cache_key(f, *args, **kwargs):
            fname, _ = function_namespace(f)
            if callable(make_name):
                altfname = make_name(fname)
            else:
                altfname = fname

            updated = altfname + json.dumps(dict(
                args=self._extract_self_arg(f, args),
                kwargs=kwargs), sort_keys=True)

            return b64encode(
                sha256(updated.encode('utf-8')).digest()
            )[:16].decode('utf-8')

        return make_cache_key

    @staticmethod
    def _extract_self_arg(f, args):
        argspec_args = inspect.getfullargspec(f).args
        if argspec_args and argspec_args[0] in ('self', 'cls'):
            return args[1:]
        return args


cache = ResourceCache(config={
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_URL': settings_container.get(APP_ENV).CACHE_REDIS_URL,
    'CACHE_DEFAULT_TIMEOUT': settings_container.get(APP_ENV).CACHE_REDIS_URL
})