当前位置: 首页>>代码示例>>Python>>正文


Python jinja2.Environment方法代码示例

本文整理汇总了Python中jinja2.Environment方法的典型用法代码示例。如果您正苦于以下问题:Python jinja2.Environment方法的具体用法?Python jinja2.Environment怎么用?Python jinja2.Environment使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jinja2的用法示例。


在下文中一共展示了jinja2.Environment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __init__(self, web_path, examples):
    """
    """
    tmpl_path = web_path + '/templates'
    static_path = web_path + '/static'
    jinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path))

    self.application = tornado.wsgi.WSGIApplication([
        (r'/', MainHandler, {
            'jinja2_env': jinja2_env,
            'examples': examples
        }),
        (r'/html', HtmlHandler, {
            'examples': examples
        }),
        (r'/features', FeaturesHandler, {
            'jinja2_env': jinja2_env,
            'examples': examples
        }),
        (r'/static/(.*)', tornado.web.StaticFileHandler, {
            'path': static_path
        }),
    ]) 
开发者ID:google-research-datasets,项目名称:natural-questions,代码行数:25,代码来源:nq_browser.py

示例2: render

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def render(search_root, project):
    template_paths = []
    matrix_dirs = []

    # traverse filesystem once and find out all matrix.yml and templates
    for cur_dir, dirs, files in os.walk(search_root):
        # TODO: hornor .gitignore
        for f in files:
            if f == 'matrix.yml':
                logger.info('Found matrix in %s', cur_dir)
                matrix_dirs.append(cur_dir)
            elif f.endswith('.jinja'):
                template_paths.append(os.path.join(cur_dir, f))

    # register templates with jinja environment
    jinja2_env = jinja2.Environment(loader=FilesLoader(template_paths))

    for maxtrix_dir in matrix_dirs:
        if project and os.path.basename(maxtrix_dir) != project:
            continue
        render_matrix(jinja2_env, maxtrix_dir) 
开发者ID:floydhub,项目名称:dockerfiles,代码行数:23,代码来源:render.py

示例3: render_publications

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def render_publications():
    from jinja2 import FileSystemLoader, Environment
    sys.path.append('.')
    import bibparse

    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('publications_templ.rst')

    with open('publications.bib') as f:
        bib = f.read()

    if len(bib) == 0:
        return False

    pubs = bibparse.entries.parseString(bib)
    # Reverse chronological order
    pubs = sorted(pubs, key=lambda x: -int(x.fields['year']))

    with open('publications.rst', 'w') as f:
        f.write(template.render(publications=pubs))
    return True 
开发者ID:msmbuilder,项目名称:mdentropy,代码行数:23,代码来源:conf.py

示例4: get_source

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def get_source(
            self,
            _env: jinja2.Environment,
            template: str
    ) -> typing.Tuple[str, str, typing.Callable[[], bool]]:
        path = os.path.join(self._subdir, template)
        try:
            source = utils.read_file(path)
        except OSError as e:
            source = html_fallback.replace("%ERROR%", html.escape(str(e)))
            source = source.replace("%FILE%", html.escape(template))
            log.misc.exception("The {} template could not be loaded from {}"
                               .format(template, path))
        # Currently we don't implement auto-reloading, so we always return True
        # for up-to-date.
        return source, path, lambda: True 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:18,代码来源:jinja.py

示例5: __init__

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __init__(self, template_file=None, flag_dep=False):
        """Constructor

        The `Diagram` class constructor simply initializes object lists.  It
        does not create objects or relationships.
        """
        self._flag_dep = flag_dep
        self.clear()
        loader_list = []
        if template_file is not None:
            loader_list.append(jinja2.FileSystemLoader(
                os.path.abspath(os.path.dirname(template_file))))
            self._template_file = os.path.basename(template_file)
        else:
            self._template_file = 'default.puml'
        loader_list.append(jinja2.PackageLoader('hpp2plantuml', 'templates'))
        self._env = jinja2.Environment(loader=jinja2.ChoiceLoader(
            loader_list), keep_trailing_newline=True) 
开发者ID:thibaultmarin,项目名称:hpp2plantuml,代码行数:20,代码来源:hpp2plantuml.py

示例6: _init

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def _init(cls):

        if cls.package_name is None:
            raise NotImplementedError("Package name not given")

        if cls.spec_template_file is None:
            raise NotImplementedError("Spec file not given")

        loader = PackageLoader(cls.package_name, "")
        env = Environment(loader=loader)
        template = env.get_template(cls.spec_template_file)
        tdict = yaml.safe_load(StringIO(template.render()))
        tdict = jsonref.loads(json.dumps(tdict))

        # TODO - Check if keys are present
        cls.provider_spec = tdict["components"]["schemas"]["provider_spec"]
        cls.Validator = StrictDraft7Validator(cls.provider_spec) 
开发者ID:nutanix,项目名称:calm-dsl,代码行数:19,代码来源:base.py

示例7: _render_config_template

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def _render_config_template(
    ip,
    port,
    username,
    password,
    project_name,
    log_level,
    schema_file="config.ini.jinja2",
):
    """renders the config template"""

    loader = PackageLoader(__name__, "")
    env = Environment(loader=loader)
    template = env.get_template(schema_file)
    text = template.render(
        ip=ip,
        port=port,
        username=username,
        password=password,
        project_name=project_name,
        log_level=log_level,
    )
    return text.strip() + os.linesep 
开发者ID:nutanix,项目名称:calm-dsl,代码行数:25,代码来源:config.py

示例8: __init__

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __init__(self, redmine_server, redmine_api_key, project_name_or_identifier, issues_dirname, redmine2github_id_map_filename):
        """
        Constructor
        
        :param redmine_server: str giving the url of the redmine server.  e.g. https://redmine.myorg.edu/
        :param redmine_api_key: str with a redmine api key
        :param project_name_or_identifier: str or int with either the redmine project id or project identifier
        :param issues_base_directory: str, directory to download the redmine issues in JSON format.  Directory will be crated
        """
        self.redmine_server = redmine_server
        self.redmine_api_key = redmine_api_key
        self.project_name_or_identifier = project_name_or_identifier
        self.issue_dirname = issues_dirname
        msg('redmine2github_id_map_filename: %s' % redmine2github_id_map_filename)
        self.redmine2github_id_map = json.loads(open(redmine2github_id_map_filename, 'rU').read())
        
        self.redmine_conn = None
        self.redmine_project = None
        
        self.jinja_env = Environment(loader=PackageLoader('redmine_ticket', 'templates'))
        
        self.setup() 
开发者ID:IQSS,项目名称:redmine2github,代码行数:24,代码来源:redmine_issue_updater.py

示例9: create

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def create(self, variables, md_output, pdf_output):
        env = Environment(loader=PackageLoader('qanta', 'reporting/templates'))
        template = env.get_template(self.template)
        markdown = template.render(variables)
        if md_output is not None:
            with open(md_output, 'w') as f:
                f.write(markdown)
        try:
            import pypandoc
            pypandoc.convert_text(
                markdown,
                'pdf',
                format='md',
                outputfile=pdf_output,
                extra_args=['-V', 'geometry:margin=.75in']
            )
        except Exception as e:
            log.warn('Pandoc was not installed or there was an error calling it, omitting PDF report')
            log.warn(str(e)) 
开发者ID:Pinafore,项目名称:qb,代码行数:21,代码来源:report_generator.py

示例10: slurm

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def slurm(partition, qos, mem_per_cpu, max_time, nodelist, cpus_per_task, luigi_module, luigi_task):
    env = Environment(loader=PackageLoader('qanta', 'slurm/templates'))
    template = env.get_template('luigi-template.sh.jinja2')
    sbatch_script = template.render({
        'luigi_module': luigi_module,
        'luigi_task': luigi_task,
        'partition': partition,
        'qos': qos,
        'mem_per_cpu': mem_per_cpu,
        'max_time': max_time,
        'nodelist': nodelist,
        'cpus_per_task': cpus_per_task
    })
    tmp_file = get_tmp_filename()
    with open(tmp_file, 'w') as f:
        f.write(sbatch_script)
    shell(f'sbatch {tmp_file}')
    shell(f'rm -f {tmp_file}') 
开发者ID:Pinafore,项目名称:qb,代码行数:20,代码来源:cli.py

示例11: __init__

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __init__(self):
    super(Environment, self).__init__(
        loader=jinja2.FileSystemLoader(path.join(path.dirname(__file__), 'ui/templates')),
        extensions=[jinja2.ext.with_],
        auto_reload=options.debug,
        autoescape=True,
        trim_blocks=True,
        undefined=Undefined)
    globals()[self.__class__.__name__] = lambda: self  # singleton

    self.globals['vj4'] = vj4
    self.globals['static_url'] = lambda s: options.cdn_prefix + staticmanifest.get(s)
    self.globals['paginate'] = misc.paginate

    self.filters['nl2br'] = misc.nl2br
    self.filters['markdown'] = misc.markdown
    self.filters['json'] = json.encode
    self.filters['gravatar_url'] = misc.gravatar_url
    self.filters['format_size'] = misc.format_size
    self.filters['format_seconds'] = misc.format_seconds
    self.filters['base64_encode'] = misc.base64_encode 
开发者ID:vijos,项目名称:vj4,代码行数:23,代码来源:template.py

示例12: __make_report_supervised

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __make_report_supervised(self, dname):
        if not os.path.exists(dname):
            os.mkdir(dname)

        self.__plot_learning_curve(dname)

        env = Environment(
            loader=FileSystemLoader(
                os.path.abspath(
                    os.path.dirname(__file__)) + '/template', encoding='utf8'))
        if self.lang == 'jp':
            tmpl = env.get_template('report_jp.html.tmp')
        else:
            tmpl = env.get_template('report.html.tmp')

        html = tmpl.render(algorithms=self.algorithms,
                           scoring=self.scoring_name,
                           task=self.task,
                           data=self.data).encode('utf-8')
        fo = io.open(dname + '/report.html', 'w', encoding='utf-8')
        fo.write(html.decode('utf-8'))
        fo.close() 
开发者ID:canard0328,项目名称:malss,代码行数:24,代码来源:malss.py

示例13: generate_module_sample

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def generate_module_sample(self, fname='module_sample.py'):
        """
        Generate a module sample to be able to add in the model
        in your system for prediction.

        Parameters
        ----------
        fname : string (default="module_sample.py")
            A string containing a path to a output file.
        """

        env = Environment(
            loader=FileSystemLoader(
                os.path.abspath(
                    os.path.dirname(__file__)) + '/template', encoding='utf8'))
        tmpl = env.get_template('sample_code.py.tmp')
        encoded = True if len(self.data.del_columns) > 0 else False
        html = tmpl.render(algorithm=self.algorithms[self.best_index],
                           encoded=encoded,
                           standardize=self.standardize).encode('utf-8')
        fo = io.open(fname, 'w', encoding='utf-8')
        fo.write(html.decode('utf-8'))
        fo.close() 
开发者ID:canard0328,项目名称:malss,代码行数:25,代码来源:malss.py

示例14: __init__

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def __init__(self, *args, **kwargs):
        """Construct the expression engine."""
        super().__init__(*args, **kwargs)

        # Initialize the Jinja2 environment.
        # TODO: Should we use a sandboxed environment?
        self._environment = Environment(self)
        # Register built-in filters.
        self._environment.filters.update(builtin_filters)
        # Register custom filters.
        self._register_custom_filters()
        # Override the safe filter.
        self._environment.filters["safe"] = self._filter_mark_safe

        # Decorate all filters with our wrapper.
        for name, function in self._environment.filters.items():
            self._environment.filters[name] = self._wrap_jinja_filter(function)

        # Escape function and safe wrapper.
        self._escape = None
        self._safe_wrapper = None 
开发者ID:genialis,项目名称:resolwe,代码行数:23,代码来源:__init__.py

示例15: setup

# 需要导入模块: import jinja2 [as 别名]
# 或者: from jinja2 import Environment [as 别名]
def setup(
    app: web.Application,
    *args: Any,
    app_key: str = APP_KEY,
    context_processors: Iterable[Callable[[web.Request], Dict[str, Any]]] = (),
    filters: Optional[Iterable[Callable[..., str]]] = None,
    default_helpers: bool = True,
    **kwargs: Any
) -> jinja2.Environment:
    kwargs.setdefault("autoescape", True)
    env = jinja2.Environment(*args, **kwargs)
    if default_helpers:
        env.globals.update(GLOBAL_HELPERS)
    if filters is not None:
        env.filters.update(filters)
    app[app_key] = env
    if context_processors:
        app[APP_CONTEXT_PROCESSORS_KEY] = context_processors
        app.middlewares.append(context_processors_middleware)

    env.globals['app'] = app

    return env 
开发者ID:aio-libs,项目名称:aiohttp-jinja2,代码行数:25,代码来源:__init__.py


注:本文中的jinja2.Environment方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。