Beispiel #1
0
def create_app(config_name=None) -> Application:
    """
    App factory. Sets up routes and all plugins.
    """
    app_config = config.Config()
    app_config.from_object(settings)

    # NB: raises ConfigurationError if an object attribute is None
    config_name = (config_name or app_config['ENV'])
    app_config.from_object(getattr(config, config_name))

    # Create basic auth for services
    [
        app_config.__setitem__(key, BasicAuth(*app_config[key]))
        for key in app_config
        if key.endswith('_AUTH') and not key == "GTM_AUTH"
    ]

    app = Application(
        debug=settings.DEBUG,
        middlewares=[
            security.nonce_middleware,
            session.setup(app_config), flash.flash_middleware,
            trace.trace_middleware
        ],
        router=routing.ResourceRouter(),
    )

    # Handle 500 errors
    error_handlers.setup(app)

    # Store upper-cased configuration variables on app
    app.update(app_config)

    # Store a dict of health check urls for required services
    app.service_status_urls = app_config.get_service_urls_mapped_with_path(
        path='/info',
        excludes=[
            'ACCOUNT_SERVICE_URL', 'EQ_URL', 'WEBCHAT_SVC_URL',
            'ADDRESS_INDEX_SVC_URL', 'ADDRESS_INDEX_SVC_EXTERNAL_URL',
            'AD_LOOK_UP_SVC_URL'
        ])

    # Monkey patch the check_services function as a method to the app object
    app.check_services = types.MethodType(check_services, app)

    # Bind logger
    logger_initial_config(log_level=app['LOG_LEVEL'],
                          ext_log_level=app['EXT_LOG_LEVEL'])

    # Set up routes
    routes.setup(app, url_path_prefix=app['URL_PATH_PREFIX'])

    # Use content negotiation middleware to render JSON responses
    negotiation.setup(app)

    # Setup jinja2 environment
    env = aiohttp_jinja2.setup(app,
                               loader=jinja2.PackageLoader('app', 'templates'),
                               context_processors=[
                                   flash.context_processor,
                                   aiohttp_jinja2.request_processor,
                                   google_analytics.ga_ua_id_processor,
                                   domains.domain_processor,
                                   security.context_processor
                               ],
                               extensions=['app.i18n.i18n'])

    env.filters['setAttributes'] = jinja_filter_set_attributes
    env.install_gettext_translations(i18n, newstyle=True)

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    app.on_response_prepare.append(security.on_prepare)

    logger.info('app setup complete', config=config_name)

    return app
def create_app(config_name=None, google_auth=None) -> Application:
    """
    App factory. Sets up routes and all plugins.
    """
    app_config = config.Config()
    app_config.from_object(settings)

    # NB: raises ConfigurationError if an object attribute is None
    config_name = (config_name or app_config['ENV'])
    app_config.from_object(getattr(config, config_name))

    # Create basic auth for services
    [
        app_config.__setitem__(key, BasicAuth(*app_config[key]))
        for key in app_config if key.endswith('_AUTH')
    ]

    app = Application(
        debug=settings.DEBUG,
        middlewares=[
            security.nonce_middleware,
            session.setup(app_config),
            flash.flash_middleware,
        ],
        router=routing.ResourceRouter(),
    )

    # Handle 500 errors
    error_handlers.setup(app)

    # Store upper-cased configuration variables on app
    app.update(app_config)

    # Store a dict of health check urls for required services
    app.service_status_urls = app_config.get_service_urls_mapped_with_path(
        path='/info', excludes=['FSDR_SERVICE_URL'])

    # Monkey patch the check_services function as a method to the app object
    app.check_services = types.MethodType(check_services, app)

    # Bind logger
    logger_initial_config(log_level=app['LOG_LEVEL'],
                          ext_log_level=app['EXT_LOG_LEVEL'])

    # Set up routes
    routes.setup(app, url_path_prefix=app['URL_PATH_PREFIX'])

    # Use content negotiation middleware to render JSON responses
    negotiation.setup(app)

    # Setup jinja2 environment
    aiohttp_jinja2.setup(app,
                         loader=jinja2.PackageLoader('app', 'templates'),
                         context_processors=[
                             flash.context_processor,
                             aiohttp_jinja2.request_processor,
                             domains.domain_processor
                         ])

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    if not app.debug:
        app.on_response_prepare.append(security.on_prepare)

    # Add cache  job  role dropdowns
    app['jr_names_service'] = job_role_utils.JRNamesService()
    app['client'] = ClientSession()

    logger.info('app setup complete', config=config_name)

    return app
Beispiel #3
0
def create_app(config_name=None) -> Application:
    """App factory. Sets up routes and all plugins.
    """
    app_config = config.Config()
    app_config.from_object(settings)

    # NB: raises ConfigurationError if an object attribute is None
    config_name = (config_name or app_config["ENV"])
    app_config.from_object(getattr(config, config_name))

    # Bind logger
    logger_initial_config(service_name="respondent-home",
                          log_level=app_config["LOG_LEVEL"])
    logger.info("Logging configured",
                log_level=app_config['LOG_LEVEL'],
                config=config_name)

    # Create basic auth for services
    [
        app_config.__setitem__(key, BasicAuth(*app_config[key]))
        for key in app_config if key.endswith('_AUTH')
    ]

    app = Application(
        debug=settings.DEBUG,
        middlewares=[
            security.nonce_middleware,
            session.setup(app_config["SECRET_KEY"]),
            flash.flash_middleware,
            flash.maintenance_middleware,
        ],
        router=routing.ResourceRouter(),
    )

    # Handle 500 errors
    error_handlers.setup(app)

    # Store upper-cased configuration variables on app
    app.update(app_config)

    # Store a dict of health check urls for required services
    app.service_status_urls = app_config.get_service_urls_mapped_with_path(
        path='/info', excludes=['ACCOUNT_SERVICE_URL', 'EQ_URL'])

    # Monkey patch the check_services function as a method to the app object
    app.check_services = types.MethodType(check_services, app)

    cf = cloud.ONSCloudFoundry(redis_name=app.get('REDIS_SERVICE'))
    if cf.detected and cf.redis:
        logger.info("Cloud Foundry detected, setting service configurations",
                    redis_name=cf.redis.name)
        app['REDIS_HOST'] = cf.redis.credentials['host']
        app['REDIS_PORT'] = cf.redis.credentials['port']

    # Set up routes
    routes.setup(app, url_path_prefix=app['URL_PATH_PREFIX'])

    # Use content negotiation middleware to render JSON responses
    negotiation.setup(app)

    # Setup jinja2 environment
    env = aiohttp_jinja2.setup(
        app,
        loader=jinja2.PackageLoader("app", "templates"),
        context_processors=[
            flash.context_processor, aiohttp_jinja2.request_processor,
            google_analytics.ga_ua_id_processor
        ],
        extensions=['jinja2.ext.i18n'],
    )
    # Required to add the default gettext and ngettext functions for rendering
    env.install_null_translations()

    # JWT KeyStore
    app["key_store"] = jwt.key_store(app["JSON_SECRET_KEYS"])

    app.on_startup.append(on_startup)
    app.on_cleanup.append(on_cleanup)
    if not app.debug:
        app.on_response_prepare.append(security.on_prepare)

    logger.info("App setup complete", config=config_name)

    return app