Python jinja2.select_autoescape() Examples

The following are 30 code examples of jinja2.select_autoescape(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jinja2 , or try the search function .
Example #1
Source File: core.py    From swagger-ui-py with Apache License 2.0 6 votes vote down vote up
def __init__(self, app, app_type=None, config_path=None, config_url=None,
                 url_prefix='/api/doc', title='API doc', editor=False):

        self._app = app
        self._title = title
        self._url_prefix = url_prefix.rstrip('/')
        self._config_url = config_url
        self._config_path = config_path
        self._editor = editor

        assert self._config_url or self._config_path, 'config_url or config_path is required!'

        self._env = Environment(
            loader=FileSystemLoader(str(CURRENT_DIR.joinpath('templates'))),
            autoescape=select_autoescape(['html'])
        )

        if app_type and hasattr(self, '_{}_handler'.format(app_type)):
            getattr(self, '_{}_handler'.format(app_type))()
        else:
            self._auto_match_handler() 
Example #2
Source File: app.py    From revelation with MIT License 6 votes vote down vote up
def dispatch_request(self, request):
        env = Environment(
            loader=PackageLoader("revelation", "templates"),
            autoescape=select_autoescape(["html"]),
        )

        context = {
            "meta": self.config.get("REVEAL_META"),
            "slides": self.load_slides(
                self.presentation,
                self.config.get("REVEAL_SLIDE_SEPARATOR"),
                self.config.get("REVEAL_VERTICAL_SLIDE_SEPARATOR"),
            ),
            "config": self.config.get("REVEAL_CONFIG"),
            "theme": self.get_theme(self.config.get("REVEAL_THEME")),
            "style": self.style,
            "reloader": self.reloader,
        }

        template = env.get_template("presentation.html")

        return Response(
            template.render(**context), headers={"content-type": "text/html"}
        ) 
Example #3
Source File: message.py    From bottery with MIT License 6 votes vote down vote up
def render(message, template_name, context=None):
    context = context or {}
    base_dir = os.path.join(os.getcwd(), 'templates')
    paths = [base_dir]
    paths.extend(settings.TEMPLATES)

    env = Environment(
        loader=FileSystemLoader(paths),
        autoescape=select_autoescape(['html']))

    template = env.get_template(template_name)

    default_context = {
        'user': message.user,
        'platform': message.platform,
    }
    default_context.update(context)
    return template.render(**default_context) 
Example #4
Source File: jinja.py    From stoq-plugins-public with Apache License 2.0 6 votes vote down vote up
def decorate(self, response: StoqResponse) -> DecoratorResponse:
        """
        Decorate results using a template

        """
        results = None
        try:
            dirname = os.path.dirname(self.template)
            basename = os.path.basename(self.template)
            env = Environment(
                loader=FileSystemLoader(dirname),
                trim_blocks=True,
                lstrip_blocks=True,
                autoescape=select_autoescape(default_for_string=True, default=True),
            )
            results = env.get_template(basename).render(response=response)
        except TemplateNotFound:
            raise StoqPluginException(f'Template path not found: {self.template}')

        return DecoratorResponse(results) 
Example #5
Source File: pycoQC_report.py    From pycoQC with GNU General Public License v3.0 6 votes vote down vote up
def _get_jinja_template(self, template_file=None):
        """"""
        # First, try to read provided configuration file if given
        if template_file:
            self.logger.debug("\tTry to load provided jinja template file")
            try:
                with open(template_file) as fp:
                    template = jinja2.Template(fp.read())
                    return template
            except (FileNotFoundError, IOError, jinja2.exceptions.TemplateNotFound, jinja2.exceptions.TemplateSyntaxError):
                self.logger.debug ("\t\tFile not found, non-readable or invalid")

        # Last use the default harcoded config_dict
        self.logger.debug ("\tRead default jinja template")
        env = jinja2.Environment (
            loader=jinja2.PackageLoader('pycoQC', 'templates'),
            autoescape=jinja2.select_autoescape(["html"]))
        template = env.get_template('spectre.html.j2')
        return template 
Example #6
Source File: build_html.py    From 7billionhumans with MIT License 6 votes vote down vote up
def main():
    if OUTPUT_DIR.exists():
        shutil.rmtree(OUTPUT_DIR)
    OUTPUT_DIR.mkdir()
    env = Environment(
        loader=FileSystemLoader('templates'),
        autoescape=select_autoescape(['html', 'xml'])
    )

    template = env.get_template('index.html')
    with open(OUTPUT_DIR / 'index.html', 'w') as f:
        f.write(template.render(years=get_years()))

    render_year_pages(env)
    render_solution_pages(env)

    for file in STATIC_DIR.glob('*'):
        shutil.copy(file, OUTPUT_DIR / file.name) 
Example #7
Source File: project.py    From cloudformation-cli with Apache License 2.0 6 votes vote down vote up
def __init__(self, overwrite_enabled=False, root=None):
        self.overwrite_enabled = overwrite_enabled
        self.root = Path(root) if root else Path.cwd()
        self.settings_path = self.root / SETTINGS_FILENAME
        self.type_info = None
        self.language = None
        self._plugin = None
        self.settings = None
        self.schema = None
        self.runtime = "noexec"
        self.entrypoint = None
        self.test_entrypoint = None

        self.env = Environment(
            trim_blocks=True,
            lstrip_blocks=True,
            keep_trailing_newline=True,
            loader=PackageLoader(__name__, "templates/"),
            autoescape=select_autoescape(["html", "htm", "xml", "md"]),
        )

        self.env.filters["escape_markdown"] = escape_markdown

        LOG.debug("Root directory: %s", self.root) 
Example #8
Source File: publish.py    From guildai with Apache License 2.0 6 votes vote down vote up
def _init_file_template(path, run_dest=None, filters=None):
    """Returns template for path or None if path is not a text file.

    Raises TemplateError if path does not exist or cannot be parsed as
    a template.
    """
    if not os.path.exists(path):
        raise TemplateError("%s does not exist" % path)
    if not util.is_text_file(path):
        return None
    dirname, basename = os.path.split(path)
    templates_home = _local_path("templates")
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader([dirname, templates_home]),
        autoescape=jinja2.select_autoescape(['html', 'xml']),
    )
    RunFilters(run_dest).install(env)
    if filters:
        env.filters.update(filters)
    try:
        return env.get_template(basename)
    except jinja2.TemplateError as e:
        raise TemplateError(e) 
Example #9
Source File: yaml_manager.py    From azure-functions-devops-build with MIT License 5 votes vote down vote up
def __init__(self, language, app_type):
        """Inits YamlManager as to be able generate the yaml files easily"""
        self._language = language
        self._app_type = app_type
        self.jinja_env = Environment(
            loader=FileSystemLoader(path.join(path.abspath(path.dirname(__file__)), 'templates')),
            autoescape=select_autoescape(['jinja'])
        ) 
Example #10
Source File: templating.py    From BlackSheep with MIT License 5 votes vote down vote up
def use_templates(app, loader: PackageLoader, enable_async: bool = False):
    env = getattr(app, 'jinja_environment', None)
    if not env:
        env = Environment(
            loader=loader,
            autoescape=select_autoescape(['html', 'xml']),
            auto_reload=app.debug,
            enable_async=enable_async
        )

        app.jinja_environment = env
        app.templates_environment = env

        if isinstance(app.services, Container):
            def get_jinja_env() -> Environment:
                return env

            app.services.add_singleton_by_factory(get_jinja_env)
            app.services.add_alias('jinja_environment', Environment)
            app.services.add_alias('jinja', Environment)
            app.services.add_alias('templates_environment', Environment)
        elif isinstance(app.services, Services):
            app.services['jinja_environment'] = env
            app.services['jinja'] = env
            app.services['templates_environment'] = env
        else:
            raise RuntimeError('Application services must be either `rodi.Services` or `rodi.Container`.')
        env.globals['app'] = app

    if enable_async:
        async def async_view(name: str, *args, **kwargs):
            return get_response(await render_template_async(env.get_template(template_name(name)), *args, **kwargs))

        return async_view

    def sync_view(name: str, *args, **kwargs):
        return get_response(render_template(env.get_template(template_name(name)), *args, **kwargs))

    return sync_view 
Example #11
Source File: test_generate_chart.py    From litmus with Apache License 2.0 5 votes vote down vote up
def verify_generated_artifact(template_file, config_file, expected_file):
    env = Environment(loader = FileSystemLoader('./'), trim_blocks=True, lstrip_blocks=True, autoescape=select_autoescape(['yaml']))
    tmpl = env.get_template(template_file)
    output_from_parsed_template = tmpl.render(config_file)
    with open('test_generated_artifact.yml', "w+") as f:
        f.write(output_from_parsed_template)
    comparison_result = filecmp.cmp('test_generated_artifact.yml', expected_file)
    return comparison_result 
Example #12
Source File: workflow_report.py    From sos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_report(output_file, workflow_id):
    data = WorkflowSig(workflow_id)

    from jinja2 import Environment, PackageLoader, select_autoescape
    environment = Environment(
        loader=PackageLoader('sos', 'templates'),
        autoescape=select_autoescape(['html', 'xml']))
    environment.filters['basename'] = os.path.basename
    template = environment.get_template('workflow_report.tpl')

    context = {
        'workflows': data.workflows(),
        'tasks': data.tasks(),
        'steps': data.steps(),
        'transcripts': data.transcripts(),
        'sos_version': __version__,
        'user': getpass.getuser(),
        'time_now_str': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),
    }
    # derived context
    context['master_id'] = next(iter(
        context['workflows'].values()))['master_id']
    try:
        # calculate percentage
        start_time = context['workflows'][context['master_id']]['start_time']
        total_duration = context['workflows'][
            context['master_id']]['end_time'] - start_time
        for info in context['workflows'].values():
            calc_timeline(info, start_time, total_duration)
        for steps in context['steps'].values():
            for step in steps:
                calc_timeline(step, start_time, total_duration)
        for info in context['tasks'].values():
            calc_timeline(info, start_time, total_duration)
        with open(output_file, 'w') as wo:
            wo.write(template.render(context))
        env.logger.info(f'Summary of workflow saved to {output_file}')
    except Exception as e:
        env.logger.error(f'Failed to generate report {output_file}: {e}') 
Example #13
Source File: render.py    From cmake_format with GNU General Public License v3.0 5 votes vote down vote up
def get_html(node, fullpage=False):
  """
  Return a string containing html markup of the annoted listfile which has
  been parsed into the parse tree rooted at `node`.
  """

  outfile = io.StringIO()
  dump_html(node, outfile)
  content = outfile.getvalue()
  if not fullpage:
    return content

  tpl_kwargs = {"content": content}

  try:
    import jinja2
  except ImportError:
    logging.error(
        "Cannot import jinja. Please install jinja in your python environment"
        " to use the fullpage html renderer")
    return None

  thisdir = os.path.realpath(os.path.dirname(__file__))
  tpldir = os.path.join(thisdir, "templates")
  env = jinja2.Environment(
      loader=jinja2.FileSystemLoader(tpldir),
      autoescape=jinja2.select_autoescape(["html"])
  )

  stylesheet_path = os.path.join(tpldir, "style.css")

  with io.open(stylesheet_path, "r", encoding="utf-8") as infile:
    tpl_kwargs["stylesheet"] = infile.read()

  template = env.get_template("layout.html.tpl")
  return template.render(**tpl_kwargs) 
Example #14
Source File: server.py    From syzygy-tables.info with GNU Affero General Public License v3.0 5 votes vote down vote up
def make_app(config):
    app = aiohttp.web.Application(middlewares=[trust_x_forwarded_for])
    app["config"] = config

    # Check configured base url.
    assert config.get("server", "base_url").startswith("http")
    assert config.get("server", "base_url").endswith("/")

    # Configure templating.
    app["jinja"] = jinja2.Environment(
        loader=jinja2.FileSystemLoader("templates"),
        autoescape=jinja2.select_autoescape(["html"]))
    app["jinja"].globals["DEFAULT_FEN"] = DEFAULT_FEN
    app["jinja"].globals["STARTING_FEN"] = chess.STARTING_FEN
    app["jinja"].globals["development"] = config.getboolean("server", "development")
    app["jinja"].globals["asset_url"] = asset_url
    app["jinja"].globals["kib"] = kib

    # Load stats.
    with open("stats.json") as f:
        app["stats"] = json.load(f)

    # Setup routes.
    app.router.add_routes(routes)
    app.router.add_static("/static", "static")
    app.router.add_route("GET", "/checksums/bytes.tsv", static("checksums/bytes.tsv"))
    app.router.add_route("GET", "/checksums/tbcheck.txt", static("checksums/tbcheck.txt", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/PackManifest", static("checksums/PackManifest", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/B2SUM", static("checksums/B2SUM", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/MD5SUM", static("checksums/MD5SUM", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/SHA1SUM", static("checksums/SHA1SUM", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/SHA256SUM", static("checksums/SHA256SUM", content_type="text/plain"))
    app.router.add_route("GET", "/checksums/SHA512SUM", static("checksums/SHA512SUM", content_type="text/plain"))
    app.router.add_route("GET", "/endgames.pgn", static("stats/regular/maxdtz.pgn", content_type="application/x-chess-pgn"))
    app.router.add_route("GET", "/stats.json", static("stats.json"))
    return app 
Example #15
Source File: report.py    From arche with MIT License 5 votes vote down vote up
def __init__(self):
        self.results: Dict[str, Result] = {}

        self.env = Environment(
            loader=PackageLoader("arche", "templates"),
            autoescape=select_autoescape(["html"]),
            extensions=["jinja2.ext.loopcontrols"],
        )
        self.env.filters["linkify"] = linkify 
Example #16
Source File: smtp_mailer.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def __init__(self, opts, mail_context):
        self.opts = opts
        self.mail_context = mail_context

        self.from_address = self.mail_context['mail_from']
        self.to_address_list = self.mail_context['mail_to']
        self.cc_address_list = self.mail_context['mail_cc']
        self.bcc_address_list = self.mail_context['mail_bcc']
        self.mail_subject = self.mail_context['mail_subject']
        self.attachment_list = self.mail_context['mail_attachments']

        self.smtp_config_section = self.opts.get(CONFIG_DATA_SECTION, {})
        self.smtp_server = self.smtp_config_section.get("smtp_server")
        self.smtp_port = str(self.smtp_config_section.get("smtp_port", SMTP_DEFAULT_PORT))
        self.smtp_cafile = self.smtp_config_section.get("smtp_ssl_cafile", False)

        if self.smtp_cafile in ['False', 'false']:
            self.smtp_cafile = False
        elif self.smtp_cafile in ['True', 'true']:
            self.smtp_cafile = True

        self.smtp_user = self.smtp_config_section.get("smtp_user")
        self.smtp_password = self.smtp_config_section.get("smtp_password")

        self.smtp_conn_timeout = int(self.smtp_config_section.get("smtp_conn_timeout", SMTP_DEFAULT_CONN_TIMEOUT))
        self.options = opts.get(CONFIG_DATA_SECTION, {})

        self.jinja_env = Environment(autoescape=select_autoescape(['html']),
                                     extensions=['jinja2.ext.do'])
        self.jinja_env.globals['template_helper'] = TemplateHelper(self) 
Example #17
Source File: template.py    From PyPlanet with GNU General Public License v3.0 5 votes vote down vote up
def environment(self):
		if not self._environment:
			self._environment = Environment(
				enable_async=True,
				loader=PyPlanetLoader.get_loader(),
				autoescape=select_autoescape(['html', 'xml', 'Txt', 'txt', 'ml', 'ms', 'script.txt', 'Script.Txt']),
				auto_reload=bool(settings.DEBUG),
			)
		return self._environment 
Example #18
Source File: __init__.py    From adr-viewer with MIT License 5 votes vote down vote up
def render_html(config):

    env = Environment(
        loader=PackageLoader('adr_viewer', 'templates'),
        autoescape=select_autoescape(['html', 'xml'])
    )

    template = env.get_template('index.html')

    return template.render(config=config) 
Example #19
Source File: jinja2.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def __init__(self, package_name, template_dir):
        self.template_env = Environment(
            loader=PackageLoader(package_name, template_dir),
            autoescape=select_autoescape(['html'])
        ) 
Example #20
Source File: jinja2.py    From Python-Programming-Blueprints with MIT License 5 votes vote down vote up
def __init__(self, package_name, template_dir):
        self.template_env = Environment(
            loader=PackageLoader(package_name, template_dir),
            autoescape=select_autoescape(['html'])
        ) 
Example #21
Source File: template.py    From BAG_framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def new_template_env(parent_package, tmp_folder):
    # type: (str, str) -> Environment
    return Environment(trim_blocks=True,
                       lstrip_blocks=True,
                       keep_trailing_newline=True,
                       autoescape=select_autoescape(default_for_string=False),
                       loader=PackageLoader(parent_package, package_path=tmp_folder),
                       enable_async=False,
                       ) 
Example #22
Source File: github_yaml_manager.py    From azure-functions-devops-build with MIT License 5 votes vote down vote up
def __init__(self, language, app_type, github_pat, github_repository):
        super(GithubYamlManager, self).__init__(pat=github_pat)
        self._github_repo_mgr = GithubRepositoryManager(pat=github_pat)
        self._github_repository = github_repository
        self._language = language
        self._app_type = app_type
        self.jinja_env = Environment(
            loader=FileSystemLoader(path.join(path.abspath(path.dirname(__file__)), 'templates')),
            autoescape=select_autoescape(['jinja'])
        ) 
Example #23
Source File: utils.py    From odoo13-x64 with GNU General Public License v3.0 4 votes vote down vote up
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple('.' + x.lstrip('.').lower()
                             for x in enabled_extensions)
    disabled_patterns = tuple('.' + x.lstrip('.').lower()
                              for x in disabled_extensions)
    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default
    return autoescape 
Example #24
Source File: io.py    From Clash-Royale-Clan-Tools with GNU General Public License v3.0 4 votes vote down vote up
def parse_templates(config, history, tempdir, clan, members, former_members, current_war, recent_wars, suggestions, scoring_rules): # pragma: no coverage
    # Create environment for template parser
    env = Environment(
        loader=PackageLoader('crtools', 'templates'),
        autoescape=select_autoescape(['html', 'xml']),
        undefined=StrictUndefined
    )

    hidden_columns = []
    for key, value in MEMBER_TABLE_CSS_MAPPING.items():
        if config['member_table'][key] != True:
            hidden_columns.append(value)

    dashboard_html = env.get_template('page.html.j2').render(
        version           = __version__,
        config            = config,
        strings           = config['strings'],
        update_date       = datetime.now().strftime('%c'),
        members           = members,
        clan              = clan,
        clan_hero         = config['paths']['description_html_src'],
        current_war       = current_war,
        recent_wars       = recent_wars,
        suggestions       = suggestions,
        scoring_rules     = scoring_rules,
        former_members    = former_members,
        hidden_columns    = hidden_columns
    )

    write_object_to_file(os.path.join(tempdir, 'index.html'), dashboard_html)
    write_object_to_file(os.path.join(tempdir, HISTORY_FILE_NAME), history)

    # If canonical URL is provided, also render the robots.txt and
    # sitemap.xml
    if config['www']['canonical_url'] != False:
        lastmod = config['crtools']['timestamp'].replace(tzinfo=timezone.utc).isoformat()
        sitemap_xml = env.get_template('sitemap.xml.j2').render(
                url     = config['www']['canonical_url'],
                lastmod = lastmod
            )
        robots_txt = env.get_template('robots.txt.j2').render(
                canonical_url = config['www']['canonical_url']
            )
        write_object_to_file(os.path.join(tempdir, 'sitemap.xml'), sitemap_xml)
        write_object_to_file(os.path.join(tempdir, 'robots.txt'), robots_txt) 
Example #25
Source File: utils.py    From PhonePi_SampleServer with MIT License 4 votes vote down vote up
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple('.' + x.lstrip('.').lower()
                             for x in enabled_extensions)
    disabled_patterns = tuple('.' + x.lstrip('.').lower()
                              for x in disabled_extensions)
    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default
    return autoescape 
Example #26
Source File: utils.py    From EDCOP with Apache License 2.0 4 votes vote down vote up
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple('.' + x.lstrip('.').lower()
                             for x in enabled_extensions)
    disabled_patterns = tuple('.' + x.lstrip('.').lower()
                              for x in disabled_extensions)
    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default
    return autoescape 
Example #27
Source File: utils.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple('.' + x.lstrip('.').lower()
                             for x in enabled_extensions)
    disabled_patterns = tuple('.' + x.lstrip('.').lower()
                              for x in disabled_extensions)
    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default
    return autoescape 
Example #28
Source File: utils.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def select_autoescape(
    enabled_extensions=("html", "htm", "xml"),
    disabled_extensions=(),
    default_for_string=True,
    default=False,
):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)
    disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)

    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default

    return autoescape 
Example #29
Source File: __init__.py    From NSC_BUILDER with MIT License 4 votes vote down vote up
def start(*start_urls, **kwargs):
	_start_args.update(kwargs)
	if 'options' in kwargs:
		if _start_args['suppress_error']:
			_start_args.update(kwargs['options'])
		else:
			raise RuntimeError(api_error_message)

	if _start_args['port'] == 0:
		sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		sock.bind(('localhost', 0))
		_start_args['port'] = sock.getsockname()[1]
		sock.close()

	if _start_args['jinja_templates'] != None:
		from jinja2 import Environment, FileSystemLoader, select_autoescape
		templates_path = os.path.join(root_path, _start_args['jinja_templates'])
		_start_args['jinja_env'] = Environment(loader=FileSystemLoader(templates_path),
								 autoescape=select_autoescape(['html', 'xml']))


	# Launch the browser to the starting URLs
	show(*start_urls)

	def run_lambda():
		if _start_args['all_interfaces'] == True:
			HOST = '0.0.0.0'
		else:
			HOST = _start_args['host']

		app = _start_args['app']  # type: btl.Bottle
		for route_path, route_params in BOTTLE_ROUTES.items():
			route_func, route_kwargs = route_params
			btl.route(path=route_path, callback=route_func, **route_kwargs)
		if _start_args['ssl_cert']==False or _start_args['ssl_key']==False:	
			return btl.run(
				host=HOST,
				port=_start_args['port'],
				server=wbs.GeventWebSocketServer,
				quiet=True,
				app=app
				)
		else:
			ssldict = {'keyfile': _start_args['ssl_key'], 'certfile': _start_args['ssl_cert']}
			return btl.run(
				host=HOST,
				port=_start_args['port'],
				server=wbs.GeventWebSocketServer,
				quiet=True,
				app=app, 
				**ssldict)

	# Start the webserver
	if _start_args['block']:
		run_lambda()
	else:
		spawn(run_lambda) 
Example #30
Source File: utils.py    From android_universal with MIT License 4 votes vote down vote up
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
                      disabled_extensions=(),
                      default_for_string=True,
                      default=False):
    """Intelligently sets the initial value of autoescaping based on the
    filename of the template.  This is the recommended way to configure
    autoescaping if you do not want to write a custom function yourself.

    If you want to enable it for all templates created from strings or
    for all templates with `.html` and `.xml` extensions::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            enabled_extensions=('html', 'xml'),
            default_for_string=True,
        ))

    Example configuration to turn it on at all times except if the template
    ends with `.txt`::

        from jinja2 import Environment, select_autoescape
        env = Environment(autoescape=select_autoescape(
            disabled_extensions=('txt',),
            default_for_string=True,
            default=True,
        ))

    The `enabled_extensions` is an iterable of all the extensions that
    autoescaping should be enabled for.  Likewise `disabled_extensions` is
    a list of all templates it should be disabled for.  If a template is
    loaded from a string then the default from `default_for_string` is used.
    If nothing matches then the initial value of autoescaping is set to the
    value of `default`.

    For security reasons this function operates case insensitive.

    .. versionadded:: 2.9
    """
    enabled_patterns = tuple('.' + x.lstrip('.').lower()
                             for x in enabled_extensions)
    disabled_patterns = tuple('.' + x.lstrip('.').lower()
                              for x in disabled_extensions)
    def autoescape(template_name):
        if template_name is None:
            return default_for_string
        template_name = template_name.lower()
        if template_name.endswith(enabled_patterns):
            return True
        if template_name.endswith(disabled_patterns):
            return False
        return default
    return autoescape