Exemplo n.º 1
0
def init():
    BASE_DIR = os.getcwd()  # 项目路径
    STATIC_DIR = os.path.join(BASE_DIR, 'static')  # 静态文件路径
    TEMPLATE_DIR = os.path.join(BASE_DIR, 'template')  # 模版HTML路径
    app = aiohttp.web.Application(middlewares=[middleware_allow])  #
    routes = gb.var['routes']
    secret_key = 'This is the default secret_key'
    secret_key = hashlib.md5(base64.b64encode(
        secret_key.encode())).hexdigest().encode()
    setup(app, EncryptedCookieStorage(secret_key))

    aiohttp_jinja2.setup(app,
                         loader=jinja2.FileSystemLoader(TEMPLATE_DIR),
                         variable_start_string='{{{',
                         variable_end_string='}}}',
                         enable_async=True,
                         context_processors=[aiohttp_jinja2.request_processor])
    app.router.add_static('/static/', path=STATIC_DIR, name='static')
    app.router.add_routes(routes)
    aiohttp_jinja2.get_env(app).globals.update(gb.var['templateFuncClassDic'])
    print(
        f"\033[1;32;45m*** creat {len(gb.var['global_route'].routes)} route ***\033[0m"
    )
    app.router.add_routes(gb.var['global_route'].routes)
    return app
Exemplo n.º 2
0
def test_get_env():
    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({"tmpl.jinja2": "tmpl"}))

    env = aiohttp_jinja2.get_env(app)
    assert isinstance(env, jinja2.Environment)
    assert env is aiohttp_jinja2.get_env(app)
def test_get_env(loop):
    app = web.Application(loop=loop)
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': "tmpl"}))

    env = aiohttp_jinja2.get_env(app)
    assert isinstance(env, jinja2.Environment)
    assert env is aiohttp_jinja2.get_env(app)
Exemplo n.º 4
0
        def go():
            app = web.Application(loop=self.loop)
            aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
                {'tmpl.jinja2': "tmlp"}))

            env = aiohttp_jinja2.get_env(app)
            self.assertIsInstance(env, jinja2.Environment)
            self.assertIs(env, aiohttp_jinja2.get_env(app))
        def go():
            app = web.Application(loop=self.loop)
            aiohttp_jinja2.setup(app,
                                 loader=jinja2.DictLoader(
                                     {'tmpl.jinja2': "tmlp"}))

            env = aiohttp_jinja2.get_env(app)
            self.assertIsInstance(env, jinja2.Environment)
            self.assertIs(env, aiohttp_jinja2.get_env(app))
Exemplo n.º 6
0
def run(config_file, bootstrap_port, path):
    """Starts the app as defined in the config file.

    Starts the app in bootstrap mode if the bootstrap port is set via --bootstrap-port."""
    config = load_config(config_file)

    loop = asyncio.get_event_loop()

    app_config_name = list(config.keys())[0]

    try:
        app_class = server_app_registry.get_plugin(app_config_name)
    except ValueError as e:
        raise click.UsageError(*e.args)

    if bootstrap_port:
        if app_class is AcmeCA:
            raise click.UsageError(
                f"Bootstrapping is not supported for the {app_class} at this moment."
            )

        click.echo(
            f"Starting {app_class.__name__} in bootstrap mode on port {bootstrap_port}"
        )
        app_config = config[app_config_name]

        app_config["port"] = bootstrap_port
        app_config[
            "challenge_validator"] = "dummy"  # Do not validate challenges
        app_config["subnets"] = [
            "127.0.0.1/32",
            "10.110.0.0/24",
        ]  # Only allow localhost and the docker bridge network
        # Bootstrap app does not run behind a reverse proxy:
        app_config["use_forwarded_header"] = False
        app_config["require_eab"] = False
    else:
        click.echo(f"Starting {app_class.__name__}")

    if issubclass(app_class, AcmeRelayBase):
        runner, site = loop.run_until_complete(
            run_relay(config, path, app_class, app_config_name))
    elif app_class is AcmeCA:
        runner, site = loop.run_until_complete(run_ca(config, path))
    else:
        raise ValueError(app_class)

    aiohttp_jinja2.setup(site.app, loader=jinja2.FileSystemLoader("./tpl/"))
    aiohttp_jinja2.get_env(site.app).globals.update({"url_for": _url_for})

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        loop.run_until_complete(runner.cleanup())
Exemplo n.º 7
0
def _prepare_prayer_response_factory(response, character, app):
    response['close'] = False
    response['#prepared-prayers'] = {
        'data':
        get_env(app).get_template('character_prepared_prayers.html').render(
            prayers=PRAYERS, character=character)
    }
    response['#prayer-slots'] = {
        'data':
        get_env(app).get_template('character_prayer_slots.html').render(
            character=character)
    }
Exemplo n.º 8
0
def _prepare_spell_response_factory(response, character, app):
    response['close'] = False
    response['#prepared-spells'] = {
        'data':
        get_env(app).get_template('character_prepared_spells.html').render(
            spells=SPELLS, character=character)
    }
    response['#spell-slots'] = {
        'data':
        get_env(app).get_template('character_spell_slots.html').render(
            character=character)
    }
Exemplo n.º 9
0
def _prayer_response_factory(response, character, app):
    response['#prayer-accordion'] = {
        'data':
        get_env(app).get_template('character_prayers_display.html').render(
            prayers=PRAYERS, character=character),
        'activateTooltip':
        True
    }
    response['#prayer-slots'] = {
        'data':
        get_env(app).get_template('character_prayer_slots.html').render(
            character=character)
    }
Exemplo n.º 10
0
def _spell_response_factory(response, character, app):
    response['#spell-accordion'] = {
        'data':
        get_env(app).get_template('character_spells_display.html').render(
            spells=SPELLS, character=character),
        'activateTooltip':
        True
    }
    response['#spell-slots'] = {
        'data':
        get_env(app).get_template('character_spell_slots.html').render(
            character=character)
    }
Exemplo n.º 11
0
    async def asyncSetUp(self) -> None:
        await super().asyncSetUp()

        # Create and place the self-signed certificate for openresty to use.
        fake_ca = trustme.CA()
        server_cert = fake_ca.issue_cert("127.0.0.1", "localhost")

        cert_path = Path(self.config_sec["client"]["server_cert"])

        first_in_chain = True
        for pem in server_cert.cert_chain_pems:
            pem.write_to_path(cert_path, append=not first_in_chain)
            first_in_chain = False

        fake_ca.cert_pem.write_to_path(cert_path, append=True)

        key_path = cert_path.parent / "resty-auto-ssl-fallback.key"
        server_cert.private_key_pem.write_to_path(key_path)

        # The environment variable is set to the server cert so that the requests module uses it (certbot).
        import os

        os.environ["REQUESTS_CA_BUNDLE"] = self.config_sec["client"][
            "server_cert"]

        # Disable SSL verification for urllib3 (acmetiny).
        import ssl

        ssl._create_default_https_context = ssl._create_unverified_context

        # Disable resty-auto-ssl
        with open("/usr/local/bin/resty-auto-ssl/dehydrated", "w") as f:
            f.write("echo 1;")

        self.nginx_proc = await asyncio.create_subprocess_shell(
            '/usr/local/openresty/nginx/sbin/nginx -g "daemon off; master_process on;"',
            None,
            None,
        )

        runner, ca = await AcmeCA.runner(self.config_sec["ca"])
        ca.register_challenge_validator(RequestIPDNSChallengeValidator())

        await ca._db._recreate()

        aiohttp_jinja2.setup(ca.app, loader=jinja2.FileSystemLoader("../tpl/"))
        aiohttp_jinja2.get_env(ca.app).globals.update({"url_for": _url_for})

        self.runner = runner
Exemplo n.º 12
0
Arquivo: base.py Projeto: M-o-a-T/moat
def get_template(app, template_name):
	"""Helper to fetch a template"""
	env = get_env(app)
	try:
		return env.get_template(template_name)
	except (KeyError, jinja2.TemplateNotFound) as e:
		raise HTTPInternalServerError(text="Template '{}' not found".format(template_name)) from e
Exemplo n.º 13
0
def main():
    loop = asyncio.get_event_loop()

    prefix = '/terial'

    app = web.Application(middlewares=[
        normalize_path_middleware(),
        prefix_middleware(prefix),
        common_exception_middleware(),
    ])
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader(str(script_dir / 'templates')),
        context_processors=[aiohttp_jinja2.request_processor],
    )
    jinja_env = aiohttp_jinja2.get_env(app)
    template_funcs.setup(jinja_env)
    jinja_env.globals['config'] = config
    jinja_env.globals['merge_dicts'] = merge_dicts
    jinja_env.globals['is_dict'] = is_dict

    routes.setup(app, prefix)

    app['executor'] = ThreadPoolExecutor(max_workers=3)

    web.run_app(app, port=9999, print=logger.info)
Exemplo n.º 14
0
def _hp_response_factory(response, character, app):
    add_classes = []
    remove_classes = []
    if character['damage'] > 0:
        add_classes.append('danger')
        remove_classes.append('success')
        remove_classes.append('warning')
    elif character['temp_hp'] < 0:
        add_classes.append('warning')
        remove_classes.append('success')
        remove_classes.append('danger')
    elif character['temp_hp'] > 0:
        add_classes.append('success')
        remove_classes.append('danger')
        remove_classes.append('warning')
    else:
        remove_classes.append('success')
        remove_classes.append('danger')
        remove_classes.append('warning')
    rest_in_peace = "" if character[
        'hp'] > -10 else "<span class=\"badge\">R.I.P</span>"
    response['#hp-form-content'] = {
        'data':
        get_env(app).get_template('character_hp_form.html').render(
            character=character, classes=CLASSES),
        'activateTooltip':
        True
    }
    response['#hp-value'] = {'data': character['hp']}
    response['#alive'] = {'data': rest_in_peace}
    response['#hp-row'] = {
        'addClass': add_classes,
        'removeClass': remove_classes
    }
Exemplo n.º 15
0
def _class_response_factory(response, character, app):
    class_list = "\n".join([
        """
<li class="list-group-item">
  {}
  <span class="label label-default">{}</span>
  <button type="button" class="btn btn-info btn-xs" data-toggle="collapse" data-parent="#class-group" data-target="#{}-info-dynamic">?</button>
</li>""".format(class_.capitalize(), character[class_], class_, class_)
        for class_ in CLASSES if character[class_] > 0
    ])
    response['#class-value'] = {'data': class_list}
    response['#prayer-section'] = {
        'collapse': "show" if character['priest'] > 0 else "hide"
    }
    response['#spells-section'] = {
        'collapse': "show" if character['wizard'] > 0 else "hide"
    }
    response['#powers-section'] = {
        'collapse': "show" if character['warlock'] > 0 else "hide"
    }
    response['#class-form-content'] = {
        'data':
        get_env(app).get_template('character_class_form.html').render(
            character=character, classes=CLASSES),
        'activateTooltip':
        True
    }
    _skill_response_factory(response, character, app)
    _spell_response_factory(response, character, app)
    _prayer_response_factory(response, character, app)
    _hp_response_factory(response, character, app)
Exemplo n.º 16
0
def setup_global_helpers(app):
    env = get_env(app)
    conf = app.config

    # set global helpers for Jinja 2

    def get_copy():
        """
        Returns the copyright string for the application.
        """
        now = datetime.now()
        return "Copyright &copy; {} {}".format(now.year, conf.site.copyright)

    def res(*args):
        return resources(args,
                         development=conf.development,
                         cache_seed=conf.cache_seed)

    try:
        ga_token = configuration.google_analytics
    except KeyError:
        ga_token = None

    def google_analytics():
        return ga_token

    helpers = {
        "copy": get_copy,
        "google_analytics": google_analytics,
        "resources": res
    }

    env.globals.update(helpers)
Exemplo n.º 17
0
def setup_templates(webapp, conf):
    templates = []

    try:
        template_modules = aio.app.config['web/%s']['modules']
    except KeyError:
        try:
            template_modules = aio.app.config["aio/web"]["modules"]
        except KeyError:
            try:
                template_modules = aio.app.config["aio"]["modules"]
            except KeyError:
                template_modules = ''

    if not template_modules:
        return

    log.debug("Setting up templates for: %s" % webapp['name'])

    for module in [x.strip() for x in template_modules.split("\n")]:
        templates.append(
            os.path.join(
                resolve(module).__path__[0], "templates"))
    env = aiohttp_jinja2.get_env(webapp)

    loader = FileSystemLoader(templates)
    env = aiohttp_jinja2.setup(webapp, loader=loader)
Exemplo n.º 18
0
async def initialize(app):
    """Initialize server."""
    # Get when the data was last modified (This will also check if DB is up)
    update_datetime = (await db.get_last_modified_date()).strftime(
        conf.datetime_format)
    LOG.info("Update datetime: %s", update_datetime)
    setattr(conf, 'update_datetime', update_datetime)

    app['static_root_url'] = '/static'

    env = aiohttp_jinja2.get_env(app)
    #update_datetime_formatted = (await get_last_modified_date()).strftime(conf.update_datetime)
    env.globals.update(
        len=len,
        max=max,
        enumerate=enumerate,
        range=range,
        conf=conf,
        now=strftime("%Y"),
        #nsamples=await get_nsamples(),
        #update_datetime=update_datetime_formatted,
    )
    env.filters['pluralize'] = pluralize_dj

    # No need to call those 2:
    # assemblyIDs = await db.fetch_assemblyids()
    # datasets = await db.fetch_datasets()
    LOG.info("Initialization done.")
Exemplo n.º 19
0
def get_template(app, template_name):
    """Helper to fetch a template"""
    env = get_env(app)
    try:
        return env.get_template(template_name)
    except (KeyError, jinja2.TemplateNotFound) as e:
        raise HTTPInternalServerError(
            text="Template '{}' not found".format(template_name)) from e
Exemplo n.º 20
0
def _coin_response_factory(response, character, app):
    for coin in COINS:
        response['#{}-tooltip'.format(coin)] = {'activateTooltip': True}
    response['#coins'] = {
        'data':
        get_env(app).get_template('character_coins.html').render(
            character=character, coins=COINS)
    }
def test_init_jinja2():
    app = web.Application()
    init_themes(app)
    init_jinja2(app)
    assert app["static_root_url"] == "/static"
    env = aiohttp_jinja2.get_env(app)
    assert env.globals["themes"] == get_mdl_themes().keys()
    assert env.globals["themes"] == app["themes"].keys()
Exemplo n.º 22
0
def get_template(app, data):
    if isinstance(data, str):
        return FormatRender(app, data)

    elif not isinstance(data, dict):
        raise NotImplementedError()

    elif 'template' in data:
        env = aiohttp_jinja2.get_env(app)
        return env.get_template(data['template'])
Exemplo n.º 23
0
 def test_filters_factory(self):
     web_app = yield from self._get_web_app()
     yield from factories.filters_factory(
         web_app,
         {'filters': (
             "my_filter "
             + "aio.web.server.tests.test_factories.example_filter")})
     env = aiohttp_jinja2.get_env(web_app)
     self.assertEqual(
         env.filters['my_filter'],
         aio.web.server.tests.test_factories.example_filter)
Exemplo n.º 24
0
 def test_templates_factory_no_config(self):
     """
     [web/TEST]
     """
     web_app = yield from self._get_web_app()
     yield from factories.templates_factory(
         web_app,
         {})
     env = aiohttp_jinja2.get_env(web_app)
     with self.assertRaises(AttributeError):
         env.list_templates()
Exemplo n.º 25
0
 def test_templates_factory_web_conf(self):
     """
     [web/TEST]
     modules = aio.web.server.tests
     """
     web_app = yield from self._get_web_app()
     yield from factories.templates_factory(
         web_app,
         {'modules': 'aio.web.server.tests'})
     env = aiohttp_jinja2.get_env(web_app)
     self.assertEqual(
         [x for x in env.list_templates(extensions=["html"])],
         ['fragments/test_fragment.html', 'test_template.html'])
Exemplo n.º 26
0
def start():
    """Start Web server."""
    config = DndConfiguration()
    # asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    app = web.Application(debug=config.server.debug)
    aiohttp_jinja2.setup(
        app,
        loader=jinja2.FileSystemLoader(
            resource_filename(Requirement.parse('dnd'), 'dnd/templates')),
        auto_reload=config.server.debug,
        context_processors=[aiohttp_login.flash.context_processor])
    aiohttp_session.setup(
        app,
        EncryptedCookieStorage(config.server.session_secret,
                               max_age=config.server.session_max_age))
    aiohttp_jinja2.get_env(app).filters['to_roman'] = toRoman
    aiohttp_jinja2.get_env(app).filters['max'] = max
    aiohttp_jinja2.get_env(app).filters['cutoff_dict'] = _cutoff_dict_filter
    app.middlewares.append(aiohttp_login.flash.middleware)

    app['db_client'] = AsyncIOMotorClient()
    app['db'] = app['db_client'].dnd

    auth_settings = {}
    for setting in config.authentication:
        auth_settings[setting.upper()] = config.authentication[setting]
    aiohttp_login.setup(app, MotorStorage(app['db']), auth_settings)

    app.router.add_static("/static/",
                          path=Path(__file__) / ".." / "static",
                          name="static")
    app.router.add_get("/", index_handler)
    app.router.add_post("/api/new-character/", new_character_data_handler)
    app.router.add_get("/{id}/{name}/", character_handler)
    app.router.add_post("/api/{id}/{attribute}/{extra}/", data_handler)
    app.router.add_post("/api/{id}/{attribute}/", data_handler)
    web.run_app(app, host=config.server.ip, port=config.server.port)
    cleanup_resources()
Exemplo n.º 27
0
 def test_templates_factory_multiple_modules(self):
     """
     [web/TEST]
     modules = aio.web.server.tests
     """
     web_app = yield from self._get_web_app()
     yield from factories.templates_factory(
         web_app,
         {'modules': 'aio.web.server.tests\naio.web.server'})
     env = aiohttp_jinja2.get_env(web_app)
     templ_list = [
         x for x in env.list_templates(extensions=["html"])]
     self.assertEqual(
         sorted(templ_list),
         ['fragments/test_fragment.html', 'test_template.html'])
Exemplo n.º 28
0
def _skill_response_factory(response, character, app):
    response['#skill-accordion'] = {
        'data':
        get_env(app).get_template('character_skills_display.html').render(
            character=character),
        'activateTooltip':
        True
    }
    response['#skill-slots'] = {
        'data':
        character['unspent_skill_slots'],
        'addClass': ["label-danger"]
        if character['unspent_skill_slots'] < 0 else ["label-default"],
        'removeClass': ["label-danger"]
        if character['unspent_skill_slots'] >= 0 else ["label-default"]
    }
Exemplo n.º 29
0
def init_jinja2(app: web.Application) -> None:
    """
    Initialize jinja2 template for application.
    """
    aiohttp_jinja2.setup(
        app,
        context_processors=[
            request_processor,
            aiohttp_jinja2.request_processor,
        ],
        loader=jinja2.FileSystemLoader(str(PROJECT_DIR / "templates")),
        default_helpers=True,
    )
    app["static_root_url"] = "/static"
    env = aiohttp_jinja2.get_env(app)
    env.globals.update(themes=app["themes"].keys())
Exemplo n.º 30
0
def test_default_template_path():
    agent = Agent("jid@server", "password")

    env = get_env(agent.web.app)
    loader = env.loader

    package_loader = loader.loaders[0]
    filesystem_loader = loader.loaders[1]

    assert type(loader) == ChoiceLoader
    assert len(loader.loaders) == 2
    assert type(package_loader) == PackageLoader
    assert type(filesystem_loader) == FileSystemLoader

    assert "agent.html" in package_loader.list_templates()
    assert "agent.html" not in filesystem_loader.list_templates()
    assert filesystem_loader.searchpath == ["."]
Exemplo n.º 31
0
def test_add_template_path():
    agent = Agent("jid@server", "password")

    agent.web.start(templates_path="/tmp/spade")

    env = get_env(agent.web.app)
    loader = env.loader

    assert type(loader) == ChoiceLoader
    assert len(loader.loaders) == 3
    assert type(loader.loaders[0]) == FileSystemLoader
    assert type(loader.loaders[1]) == PackageLoader
    assert type(loader.loaders[2]) == FileSystemLoader

    filesystem_loader = loader.loaders[0]

    assert filesystem_loader.list_templates() == []
    assert filesystem_loader.searchpath == ["/tmp/spade"]
Exemplo n.º 32
0
 def __init__(
     self, *,
     from_string=None,
     template_name=None,
     app=None,
     env=None,
 ):
     if env is not None:
         self._env = env
     elif app is not None:
         self._env = aiohttp_jinja2.get_env(app)
     else:
         self._env = None
     if from_string:
         self.template = self._env.from_string(from_string)
     elif self._env:
         self.template = self._env.get_template(template_name)
     else:
         raise ValueError()
Exemplo n.º 33
0
def test_default_template_path():
    agent = Agent("jid@server", "password")

    env = get_env(agent.web.app)
    loader = env.loader

    package_loader = loader.loaders[0]
    filesystem_loader = loader.loaders[1]

    assert type(loader) == ChoiceLoader
    assert len(loader.loaders) == 2
    assert type(package_loader) == PackageLoader
    assert type(filesystem_loader) == FileSystemLoader

    assert "internal_tpl_agent.html" in package_loader.list_templates()
    assert "internal_tpl_agent.html" not in filesystem_loader.list_templates()
    assert filesystem_loader.searchpath == ["."]

    agent.stop()
Exemplo n.º 34
0
def test_add_template_path():
    agent = Agent("jid@server", "password")

    agent.web.start(templates_path="/tmp/spade")

    env = get_env(agent.web.app)
    loader = env.loader

    assert type(loader) == ChoiceLoader
    assert len(loader.loaders) == 3
    assert type(loader.loaders[0]) == FileSystemLoader
    assert type(loader.loaders[1]) == PackageLoader
    assert type(loader.loaders[2]) == FileSystemLoader

    filesystem_loader = loader.loaders[0]

    assert filesystem_loader.list_templates() == []
    assert filesystem_loader.searchpath == ["/tmp/spade"]

    agent.stop()
Exemplo n.º 35
0
def setup_server():
    app = web.Application()

    # Add static file serving:
    app.router.add_static('/static', 'example/static')

    # Add template file serving:
    jinja_loader = jinja2.FileSystemLoader('example/templates')
    aiohttp_jinja2.setup(app, loader=jinja_loader)

    # Allows to use zip in jinja templates
    env = aiohttp_jinja2.get_env(app)
    env.globals.update(zip=zip)

    app.add_routes(define_routes())

    print(
        'Server ready, try it: http://localhost:8080/squares?values=1,2,3,4,5,6'
    )
    return app
Exemplo n.º 36
0
    def __init__(self, app):
        self.app = app
        env = get_env(app)

        if env is None:
            text = ("Template engine is not initialized, "
                    "call aiohttp_jinja2.setup(...) first"
                    "")
            # in order to see meaningful exception message both: on console
            # output and rendered page we add same message to *reason* and
            # *text* arguments.
            raise web.HTTPInternalServerError(reason=text, text=text)

        self._set_asset_paths(app)

        # We only want to refresh the webpack stats in development mode,
        # not everyone sets this setting, so let's assume it's production.
        if app.settings.DEBUG:
            app.on_response_prepare.append(self._refresh_webpack_stats)

        env.globals['asset_url_for'] = self.asset_url_for
Exemplo n.º 37
0
def _trace_render_template(func, module, args, kwargs):
    """
    Trace the template rendering
    """
    # get the module pin
    pin = Pin.get_from(aiohttp_jinja2)
    if not pin or not pin.enabled():
        return func(*args, **kwargs)

    # original signature:
    # render_template(template_name, request, context, *, app_key=APP_KEY, encoding='utf-8')
    template_name = args[0]
    request = args[1]
    env = aiohttp_jinja2.get_env(request.app)

    # the prefix is available only on PackageLoader
    template_prefix = getattr(env.loader, "package_path", "")
    template_meta = "{}/{}".format(template_prefix, template_name)

    with pin.tracer.trace("aiohttp.template", span_type=SpanTypes.TEMPLATE) as span:
        span.set_meta("aiohttp.template", template_meta)
        return func(*args, **kwargs)
Exemplo n.º 38
0
async def set_secure_headers(request, handler):
    """Add secure headers to requests.

    Parameters
    ----------
    request : aiohttp.web.Request
        The request to set secure headers on.
    handler : function
        The middleware handler function.
    Returns
    -------
    aiohttp.web.Response
        The modified response to the request.
    """
    nonce = b64encode(uuid4().bytes).decode("utf-8")
    script_src = [
        "'self'",
        "blob:",
        #   SecurePolicies.CSP().Values.nonce(nonce),
        f"'nonce-{nonce}'",
        "https://unpkg.com",
        "'unsafe-eval'",
        "'unsafe-inline'",
    ]
    style_src = [
        "'self'",
        "'unsafe-inline'",
        "https://fonts.googleapis.com/css2",
    ]
    if request.path == "/api/v1/docs":
        script_src[2] = "'unsafe-inline'"
        style_src.append("'unsafe-inline'")
    get_env(request.app).globals["csp_nonce"] = nonce
    secure_headers = deepcopy(request.app["secure_headers"])
    secure_headers.csp.script_src(*script_src).style_src(*style_src)
    resp = await handler(request)
    secure_headers.framework.aiohttp(resp)
    return resp
Exemplo n.º 39
0
def init(loop, argv):
    logging.getLogger('asyncio').addFilter(SkipTimeouts())
    #
    # define your command-line arguments here
    #
    config = get_config(argv)
    # setup application and extensions
    app = create_app(config=config)
    setup_routes(app)
    aiohttp_jinja2.setup(app,
                         loader=jinja2.PackageLoader(MAIN_APP_NAME,
                                                     'templates'))

    # create connection to the database
    app.on_startup.append(init_pg)
    # shutdown db connection on exit
    app.on_cleanup.append(close_pg)
    jinja_env = aiohttp_jinja2.get_env(app)
    jinja_env.globals['STATIC'] = '/static/'
    jinja_env.globals['_'] = app['gettext']

    # Locale settings
    return app
Exemplo n.º 40
0
def _trace_render_template(func, module, args, kwargs):
    """
    Trace the template rendering
    """
    # get the module pin
    pin = Pin.get_from(aiohttp_jinja2)
    if not pin or not pin.enabled():
        return func(*args, **kwargs)

    # original signature:
    # render_template(template_name, request, context, *, app_key=APP_KEY, encoding='utf-8')
    template_name = args[0]
    request = args[1]
    env = aiohttp_jinja2.get_env(request.app)

    # the prefix is available only on PackageLoader
    template_prefix = getattr(env.loader, 'package_path', '')
    template_meta = '{}/{}'.format(template_prefix, template_name)

    with pin.tracer.trace('aiohttp.template') as span:
        span.span_type = http.TEMPLATE
        span.set_meta('aiohttp.template', template_meta)
        return func(*args, **kwargs)
Exemplo n.º 41
0
async def create_app():
    config = read_configuration_file()
    db_pool = await attach_db(config)

    app = web.Application(middlewares=[error_middleware, babel_middleware])
    app["config"] = config
    app["db-pool"] = db_pool

    app["mailer"] = MassMailer()

    # beware of order !
    setup_session(app)
    setup_security(
        app,
        SessionIdentityPolicy(),
        DBAuthorizationPolicy(db_pool)
    )
    app.middlewares.append(aiohttp_session_flash.middleware)

    template_dir = op.join(op.dirname(op.abspath(__file__)), "templates")
    aiohttp_jinja2.setup(
        app,
        loader=FileSystemLoader(template_dir),
        context_processors=(
            aiohttp_session_flash.context_processor,
            authorized_userid_context_processor
        )
    )
    jinja2_env = aiohttp_jinja2.get_env(app)
    jinja2_env.globals['_'] = _

    setup_routes(app)

    app.on_cleanup.append(cleanup)

    return app
async def send_confirmation(request, email_address, token_data, route, subject,
                            template_name):
    config = request.app["config"]

    token = generate_token(config["application"]["secret_key"], **token_data)
    url = config["application"]["url"] + \
        str(request.app.router[route].url_for(token=token))

    env = get_env(request.app)
    template = env.get_template("auth/{}.txt".format(template_name))
    text_part = template.render(url=url)
    text_message = MIMEText(text_part, "plain")
    template = env.get_template("auth/{}.html".format(template_name))
    html_part = template.render(url=url)
    html_message = MIMEText(html_part, "html")

    message = MIMEMultipart("alternative")
    message["subject"] = "[{}] {}".format(config["application"]["site_name"],
                                          subject)
    message["to"] = email_address
    message["from"] = config["application"]["from"]
    message.attach(text_message)
    message.attach(html_message)
    await request.app["mailer"].send_urgent_message(message, email_address)
Exemplo n.º 43
0
app.router.register_route(route)

template_dirs = [
    os.path.realpath(os.path.join(settings.APPS_DIR, app_dir, 'templates'))
    for app_dir in os.listdir(settings.APPS_DIR)
]
template_dirs.append(os.path.join(settings.WEB_DIR, 'templates'))

aiohttp_jinja2.setup(
    app,
    context_processors=[
        aiohttp_jinja2.request_processor,
    ],
    loader=TemplateLoader(template_dirs)
)
env = aiohttp_jinja2.get_env(app)
env.filters['tsformat'] = tsformat
env.filters['platform_group_link'] = platform_group_link

if settings.DEBUG:
    aiohttp_debugtoolbar.setup(app, intercept_redirects=False)

for add_url in get_project_urls(settings.APPS_DIR):
    add_url(app.router)

logging.config.dictConfig(settings.LOG_SETTINGS)

logger = logging.getLogger('aiohttp.server')
app.logger = logger

async def on_prepare(request, response):
Exemplo n.º 44
0
def setup_filters(webapp, conf):
    if conf.get("filters"):
        env = aiohttp_jinja2.get_env(webapp)
        for filt in conf['filters'].split("\n"):
            name, handler = [x for x in filt.split(" ") if x]
            env.filters[name] = resolve(handler)