def get_app(with_reference_data=True):
    app = aiohttp.web.Application(middlewares=[middleware.session_middleware])

    app['dbpedia-sparql'] = functools.partial(SPARQLWrapper2,
                                              os.environ.get('DBPEDIA_ENDPOINT',
                                                             'http://dbpedia.org/sparql'))
    app['db-engine'] = sqlalchemy.create_engine(os.environ['DB_URL'])
    app['db-session'] = sqlalchemy.orm.sessionmaker(app['db-engine'])

    app.router.add_route('*', '/accident',
                         handlers.AccidentListHandler())
    app.router.add_route('*', '/accident/{accident_id}',
                         handlers.AccidentDetailHandler())
    app.router.add_route('*', '/citation',
                         handlers.CitationSubmissionHandler())
    app.router.add_route('*', '/statistics',
                         handlers.StatisticsHandler())
    app.router.add_route('*', '/reference-data',
                         handlers.ReferenceDataHandler())

    if with_reference_data:
        app['reference-data'] = get_reference_data(app)

    negotiation.setup(app)

    return app
def get_app():
    app = aiohttp.web.Application()

    app['api-url'] = os.environ['ICW_API']
    app['google-analytics-tracking-id'] = os.environ.get('GOOGLE_ANALYTICS_TRACKING_ID')
    app['api-session'] = aiohttp.ClientSession()
    app['static-url'] = '/static/'

    app.router.add_route('*', '/',
                         handlers.IndexHandler())
    app.router.add_route('*', '/incident',
                         handlers.AccidentListHandler())
    app.router.add_route('*', '/incident/{accident_id}',
                         handlers.AccidentDetailHandler())
    app.router.add_route('*', '/about-data',
                         handlers.AboutDataHandler())

    app.router.add_static(app['static-url'],
                          os.path.join(os.path.dirname(__file__), 'static'))

    negotiation.setup(app)
    aiohttp_jinja2.setup(app,
                         loader=jinja2.PackageLoader('icw.web', 'templates'),
                         context_processors=[asyncio.coroutine(lambda request: {
                             'static_url': app['static-url'],
                             'api_url': app['api-url'],
                             'google_analytics_tracking_id': app['google-analytics-tracking-id']
                         })])

    return app
def get_app():
    app = aiohttp.web.Application()

    app['api-url'] = os.environ['ICW_API']
    app['google-analytics-tracking-id'] = os.environ.get(
        'GOOGLE_ANALYTICS_TRACKING_ID')
    app['api-session'] = aiohttp.ClientSession()
    app['static-url'] = '/static/'

    app.router.add_route('*', '/', handlers.IndexHandler())
    app.router.add_route('*', '/incident', handlers.AccidentListHandler())
    app.router.add_route('*', '/incident/{accident_id}',
                         handlers.AccidentDetailHandler())
    app.router.add_route('*', '/about-data', handlers.AboutDataHandler())

    app.router.add_static(app['static-url'],
                          os.path.join(os.path.dirname(__file__), 'static'))

    negotiation.setup(app)
    aiohttp_jinja2.setup(app,
                         loader=jinja2.PackageLoader('icw.web', 'templates'),
                         context_processors=[
                             asyncio.coroutine(
                                 lambda request: {
                                     'static_url':
                                     app['static-url'],
                                     'api_url':
                                     app['api-url'],
                                     'google_analytics_tracking_id':
                                     app['google-analytics-tracking-id']
                                 })
                         ])

    return app
Example #4
0
async def init(loop):
    middle = [
        error_middleware,
        auth_middleware,
    ]

    if settings.DEBUG:
        middle.append(aiohttp_debugtoolbar.middleware)

    app = web.Application(loop=loop, middlewares=middle, debug=settings.DEBUG)
    app['websockets'] = []
    if settings.DEBUG:
        aiohttp_debugtoolbar.setup(app)

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

    await setup_models(app)
    app.on_shutdown.append(on_shutdown)
    setup_scheduler(app)

    handler = app.make_handler()
    server = loop.create_server(handler, settings.HOST, settings.PORT)
    return server, handler, app
Example #5
0
def create_app(argv) -> web.Application:
    """App factory. Sets up routes and all plugins.
    """
    middle = [
        # error_middleware,
        auth_middleware,
    ]

    if settings.DEBUG:
        middle.append(aiohttp_debugtoolbar.middleware)

    app = web.Application(middlewares=middle, debug=settings.DEBUG)
    app['websockets'] = []
    if settings.DEBUG:
        aiohttp_debugtoolbar.setup(app)

    app.on_shutdown.append(on_shutdown)

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

    from models.main import client, db
    app.client = client
    app.db = db
    app.synchronize_indexes = synchronize_indexes

    setup_scheduler(app)
    return app
Example #6
0
File: app.py Project: sloria/sir
def create_app(settings_obj=None) -> web.Application:
    """App factory. Sets up routes and all plugins.

    :param settings_obj: Object containing optional configuration overrides. May be
        a Python module or class with uppercased variables.
    """
    config = Config()
    config.from_object(settings)
    if settings_obj:  # Update with overrides
        config.from_object(settings_obj)
    app = web.Application(debug=config.DEBUG)
    # Store uppercased configuration variables on app
    app.update(config)

    # Set up routes
    routes.setup(app)
    # Set up cache
    cache.setup(app)
    # Use content negotiation middleware to render JSON responses
    negotiation.setup(app)
    # Normalize paths: https://aiohttp-utils.readthedocs.org/en/latest/modules/path_norm.html
    path_norm.setup(app)
    # Set up Github client
    github_plugin.setup(app)

    return app
Example #7
0
 def __init__(self, *args, **kwargs):
     super(GameApplication, self).__init__(*args, **kwargs)
     negotiation.setup(self)
     aiohttp_jinja2.setup(
         self, loader=jinja2.FileSystemLoader('/vagrant/templates/'))
     self.setup_routes()
     path_norm.setup(self)
     self.game = Game(self)
Example #8
0
def configure_app(app, overrides=None, setup=False):
    overrides = overrides or {}
    add_routes(app)

    if setup:
        negotiation.setup(app, **overrides)
    else:
        middleware = negotiation.negotiation_middleware(**overrides)
        app.middlewares.append(middleware)
Example #9
0
def setup_routes(app):
    # test routes
    app.router.add_route('GET', '/hello', views.hello)
    app.router.add_route('GET', '/version', views.version)
    app.router.add_route('GET', '/user/{id:[0-9a-fA-F]{32}}', views.get_user)
    app.router.add_route('POST', '/validate_profile', views.profile_validation)

    negotiation.setup(app,
                      renderers=OrderedDict([('application/json', JSONRender())
                                             ]))
    path_norm.setup(app, merge_slashes=True)
def test_renderer_no_nego(app, client):
    add_routes(app)
    negotiation.setup(app)

    res = client.get('/nonego')
    assert res.content_type == 'application/octet-stream'
    assert res.body == b'Some raw data'

    res = client.get('/nonego', headers={'Accept': 'application/json'})
    assert res.content_type == 'application/octet-stream'
    assert res.body == b'Some raw data'
Example #11
0
def test_configuration_through_app_key(app, client):
    add_routes(app)
    app[CONFIG_KEY] = {
        'RENDERERS': OrderedDict([
            ('text/html', dummy_renderer),
        ])
    }
    negotiation.setup(app)
    res = client.get('/hello')
    assert res.content_type == 'text/html'
    assert res.body == b'<p>Hello world</p>'
def get_app(with_reference_data=True):
    app = aiohttp.web.Application(middlewares=[middleware.session_middleware])

    app['dbpedia-sparql'] = functools.partial(
        SPARQLWrapper2,
        os.environ.get('DBPEDIA_ENDPOINT', 'http://dbpedia.org/sparql'))
    app['db-engine'] = sqlalchemy.create_engine(os.environ['DB_URL'])
    app['db-session'] = sqlalchemy.orm.sessionmaker(app['db-engine'])

    app.router.add_route('*', '/accident', handlers.AccidentListHandler())
    app.router.add_route('*', '/accident/{accident_id}',
                         handlers.AccidentDetailHandler())
    app.router.add_route('*', '/citation',
                         handlers.CitationSubmissionHandler())
    app.router.add_route('*', '/statistics', handlers.StatisticsHandler())
    app.router.add_route('*', '/reference-data',
                         handlers.ReferenceDataHandler())

    if with_reference_data:
        app['reference-data'] = get_reference_data(app)

    negotiation.setup(app)

    return app
Example #13
0
    template = request.app['mako_lookup'].get_template(template_name)
    text = template.render_unicode(**data)
    return web.Response(text=text, content_type=request['selected_media_type'])

##### Configuration #####

CONFIG = {
    'AIOHTTP_UTILS': {
        'RENDERERS': OrderedDict([
            ('application/json', negotiation.render_json),
            ('text/html', render_mako),
        ])
    }
}

##### Application #####

app = web.Application(router=RouterWithTemplating(), debug=True)
app['mako_lookup'] = lookup
app.update(CONFIG)
negotiation.setup(app)
app.router.add_route('GET', '/', index, template='index.html')

if __name__ == "__main__":
    run(
        app,
        app_uri='examples.mako_example:app',
        reload=True,
        port=8000,
    )
Example #14
0
    return web.Response(text=text, content_type=request['selected_media_type'])


##### Configuration #####

CONFIG = {
    'AIOHTTP_UTILS': {
        'RENDERERS':
        OrderedDict([
            ('application/json', negotiation.render_json),
            ('text/html', render_mako),
        ])
    }
}

##### Application #####

app = web.Application(router=RouterWithTemplating(), debug=True)
app['mako_lookup'] = lookup
app.update(CONFIG)
negotiation.setup(app)
app.router.add_route('GET', '/', index, template='index.html')

if __name__ == "__main__":
    run(
        app,
        app_uri='examples.mako_example:app',
        reload=True,
        port=8000,
    )
Example #15
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
Example #16
0
    # to be able to access the service.
    # TODO: this may be too permissive.
    cors = aiohttp_cors.setup(app,
                              defaults={
                                  "*":
                                  aiohttp_cors.ResourceOptions(
                                      allow_credentials=True,
                                      expose_headers="*",
                                      allow_headers="*",
                                  )
                              })
    # set up content negotiation so that clients can request
    # e.g. csv data.
    negotiation.setup(app,
                      renderers=OrderedDict([('text/plain', render_data_csv),
                                             ('text/csv', render_data_csv),
                                             ('application/json',
                                              render_data_json)]))

    cors.add(
        app.router.add_route('POST', '/query', partial(post_raw_query, hdbpp)))
    cors.add(
        app.router.add_route('POST', '/search',
                             partial(post_raw_search, hdbpp)))

    cors.add(
        app.router.add_route('POST', '/httpquery',
                             partial(post_raw_query_http, hdbpp)))

    # everything else assumed to be requests for static files
    # maybe add '/static'?
Example #17
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