示例#1
0
    def patch_templates(self):
        """Patch page templates to add Hub-related buttons"""

        self.jinja_template_vars['logo_url'] = self.hub_host + url_path_join(
            self.hub_prefix, 'logo')
        self.jinja_template_vars['hub_host'] = self.hub_host
        self.jinja_template_vars['hub_prefix'] = self.hub_prefix
        env = self.web_app.settings['jinja2_env']

        env.globals['hub_control_panel_url'] = \
            self.hub_host + url_path_join(self.hub_prefix, 'home')

        env.globals['hub_end_session_url'] = \
            self.hub_host + url_path_join(self.hub_prefix, 'end-session')

        env.globals['hub_session_ended_url'] = \
            self.hub_host + url_path_join(self.hub_prefix, 'done')

        # patch jinja env loading to modify page template
        def get_page(name):
            if name == 'page.html':
                return page_template

        orig_loader = env.loader
        env.loader = ChoiceLoader([
            FunctionLoader(get_page),
            orig_loader,
        ])
示例#2
0
    def patch_templates(self):
        """Patch page templates to add Hub-related buttons"""

        self.jinja_template_vars['logo_url'] = self.hub_host + url_path_join(
            self.hub_prefix, 'logo')
        self.jinja_template_vars['hub_host'] = self.hub_host
        self.jinja_template_vars['hub_prefix'] = self.hub_prefix
        self.jinja_template_vars[
            'hub_control_panel_url'] = self.hub_host + url_path_join(
                self.hub_prefix, 'home')

        settings = self.web_app.settings
        # patch classic notebook jinja env
        jinja_envs = []
        if 'jinja2_env' in settings:
            # default jinja env (should we do this on jupyter-server, or only notebook?)
            jinja_envs.append(settings['jinja2_env'])
        if 'notebook_jinja2_env' in settings:
            # when running with jupyter-server, classic notebook (nbclassic server extension)
            # gets its own jinja env, which needs the same patch
            jinja_envs.append(settings['notebook_jinja2_env'])

        # patch jinja env loading to get modified template, only for base page.html
        def get_page(name):
            if name == 'page.html':
                return page_template

        for jinja_env in jinja_envs:
            jinja_env.loader = ChoiceLoader(
                [FunctionLoader(get_page), jinja_env.loader])
示例#3
0
文件: hfi_calc.py 项目: bcgov/wps
async def download_result_pdf(request: HFIResultRequest,
                              _=Depends(authentication_required)):
    """ Assembles and returns PDF byte representation of HFI result. """
    try:
        logger.info('/hfi-calc/download-pdf')
        results, start_timestamp, end_timestamp = await calculate_latest_hfi_results(request)

        response = HFIResultResponse(
            start_date=start_timestamp,
            end_date=end_timestamp,
            selected_station_code_ids=request.selected_station_code_ids,
            planning_area_station_info=request.planning_area_station_info,
            selected_fire_center_id=request.selected_fire_center_id,
            planning_area_hfi_results=results,
            planning_area_fire_starts=request.planning_area_fire_starts,
            request_persist_success=False)

        fire_centres_list = await hydrate_fire_centres()

        # Loads template as string from a function
        # See: https://jinja.palletsprojects.com/en/3.0.x/api/?highlight=functionloader#jinja2.FunctionLoader
        jinja_env = Environment(loader=FunctionLoader(get_template), autoescape=True)

        pdf_bytes = generate_pdf(response, fire_centres_list, jinja_env)

        return Response(pdf_bytes)
    except Exception as exc:
        logger.critical(exc, exc_info=True)
        raise
示例#4
0
 def render_url(self, url, **kwargs):
     env = Environment(loader=FunctionLoader(self.loader))
     try:
         self.response.headers['Content-Type'] = 'text/plain'
         self.response.write(env.get_template(url).render(kwargs))
     except:
         self.response.set_status(404)
示例#5
0
    def get_environment(cls):
        """
        Create and return a jinja environment to render templates

        Downstream modules can override this method to easily make changes
        to environment
        """
        extensions = [
            'jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_',
            'jinja2.ext.loopcontrols', 'jinja2.ext.do',
            SwitchableLanguageExtension
        ]
        env = Environment(extensions=extensions,
                          loader=FunctionLoader(cls.jinja_loader_func))
        env.filters.update(cls.get_jinja_filters())

        context = Transaction().context
        locale = context.get('report_lang',
                             Transaction().language or 'en').split('_')[0]
        report_translations = context.get('report_translations')
        if report_translations and os.path.isdir(report_translations):
            translations = SwitchableTranslations(locale, report_translations,
                                                  cls.babel_domain)
        else:
            translations = SwitchableTranslations(locale)
        env.install_switchable_translations(translations)
        return env
示例#6
0
def main(jinja_dir, gn_out_dir, template_file, output_file, depfile):
    # Get GN config and parse into a dictionary.
    gnconfig = subprocess.check_output(
        ["gn", "args", "--list", "--short", "-C", gn_out_dir])
    config = dict(re.findall(GN_RE, gnconfig))

    config["node_module_version"] = getmoduleversion.get_version()

    # Fill in template.
    sys.path.append(jinja_dir)
    from jinja2 import Environment, FunctionLoader
    env = Environment(loader=FunctionLoader(load_template),
                      trim_blocks=True,
                      lstrip_blocks=True)
    env.filters["to_number"] = bool_to_number_filter
    template = env.get_template(template_file)
    rendered_template = template.render(config)

    # Write output.
    with open(output_file, "w") as f:
        f.write(rendered_template)

    # Write depfile. Force regenerating config.gypi when GN configs change.
    with open(depfile, "w") as f:
        dot_gn = os.path.abspath(os.path.join(root_dir, ".gn"))
        args_gn = os.path.abspath(os.path.join(gn_out_dir, "args.gn"))
        f.write("%s: %s %s" % (output_file, dot_gn, args_gn))
示例#7
0
    def __init__(self, templates_dir=None, transfer_method=None, debug=False):
        self.debug = debug

        if templates_dir is None:
            raise (ValueError('templates_dir must be passed to HumeRenderer'))
        if transfer_method is None:
            raise (
                ValueError('transfer_method must be passed to HumeRenderer'))

        if self.debug:
            printerr('HumeRenderer: templates_dir="{}"'.format(templates_dir))
            printerr(
                'HumeRenderer: transfer_method="{}"'.format(transfer_method))

        self.transfer_method = transfer_method
        # Setup jinja using templates_dir
        # TODO: Check Exceptions for FileSystemLoader and implement try/except
        self.tplDir = '{}/{}'.format(templates_dir, transfer_method)
        loader = FileSystemLoader(self.tplDir)
        if self.debug:
            printerr('HumeRenderer: Using tplDir = "{}"'.format(self.tplDir))
        self.jinja2 = Environment(loader=loader,
                                  trim_blocks=True)  # TODO: check need of trim
        # Configure an internal loader using a callback function.
        # useful when no template files are available, prolly broken humed install
        internal = FunctionLoader(self.internal_tpl_loader)
        self.jinja2fallback = Environment(loader=internal, trim_blocks=True)
示例#8
0
文件: util.py 项目: hmogensen/rdm
def render_from_string(input_string=None,
                       context=None,
                       config=None,
                       template_name=None,
                       input_dictionary=None):
    jinja2.clear_caches()
    if config is None:
        config = {}
    if template_name is None:
        template_name = 'input.md'
    if input_dictionary is None:
        input_dictionary = {}
    if input_string is not None:
        input_dictionary[template_name] = input_string
    if context is None:
        context = {}

    def load_string(template_name):
        return input_dictionary[template_name]

    loaders = [FunctionLoader(load_string)]

    return render_template_to_string(config,
                                     template_name,
                                     context,
                                     loaders=loaders)
示例#9
0
def get_jinja2_environment() -> Jinja2Environment:
    from jinja2 import Environment, FunctionLoader, StrictUndefined

    env = Environment(
        loader=FunctionLoader(lambda name: open(name).read()),
        undefined=StrictUndefined,
    )
    return env
def render(doc, template_args):
    def load_template(name):
        return doc

    env = Environment(loader=FunctionLoader(load_template))

    template = env.get_template('config.yaml')
    return template.render(template_args)
示例#11
0
 def render_template(cls, template_string, **context):
     """
     Render the template using Jinja2
     """
     env = Environment(loader=FunctionLoader(cls.jinja_loader_func))
     env.filters.update(cls.get_jinja_filters())
     template = env.get_template(template_string)
     return template.render(**context)
示例#12
0
def _get_rendered_value(value, context: Context):
    env = Environment(loader=FunctionLoader(lambda x: x),
                      extensions=[GetVarExtension])
    env.context = context
    try:
        return env.get_template(value).render()
    except:
        return value
示例#13
0
def func_3():
    file_loader = FunctionLoader(loadTpl)  # Передаём ссылку на функцию.
    env = Environment(loader=file_loader)

    tm = env.get_template('index_1')  # Template
    msg = tm.render(u=persons[0])

    print(msg)
示例#14
0
文件: templating.py 项目: xvzf/byceps
def create_sandboxed_environment(*, loader: Optional[BaseLoader]=None) \
                                -> Environment:
    """Create a sandboxed environment."""
    if loader is None:
        # A loader that never finds a template.
        loader = FunctionLoader(lambda name: None)

    return ImmutableSandboxedEnvironment(loader=loader, autoescape=True)
示例#15
0
 def prepare(self):
     if not self.env:
         from jinja2 import Environment, FunctionLoader
         self.env = Environment(line_statement_prefix="#", loader=FunctionLoader(self.loader))
     if self.template:
         self.tpl = self.env.from_string(self.template)
     else:
         self.tpl = self.env.get_template(self.filename)
示例#16
0
 def setUp(self):
     self.view = CSVJinjaView(
         env_options={'loader': FunctionLoader(lambda x: x)})
     self.data = [
         ['1', 'hi', 'yes', '2017-07-19', '3.5'],
         ['2', 'bye', 'no', '2017-07-18', '3.6'],
         ['3', 'heh', 'y', '2017-07-20', '3.7'],
     ]
     self.model = CSVModel(self.data)
示例#17
0
def create_sandboxed_env():
    """Create a sandboxed environment."""
    # A loader that never finds a template.
    dummy_loader = FunctionLoader(lambda name: None)

    return ImmutableSandboxedEnvironment(loader=dummy_loader,
                                         autoescape=True,
                                         lstrip_blocks=True,
                                         trim_blocks=True)
示例#18
0
def generate_job_definition(dfg, component, tester):
    """Returns a multi-line string which is the jenkins job definition

    based on the given arguments.
    """

    template = get_template(tester)
    j2_env = Environment(loader=FunctionLoader(get_template), trim_blocks=True)
    template = j2_env.get_template(tester)
    return template.render(dfg=dfg, component=component, tester=tester)
示例#19
0
def generate_job_definition(jjb_data):
    """Returns a multi-line string which is the jenkins job definition

    based on the given arguments.
    """

    template = get_template(jjb_data['tester'])
    j2_env = Environment(loader=FunctionLoader(get_template), trim_blocks=True)
    template = j2_env.get_template(jjb_data['tester'])
    return template.render(jjb=jjb_data)
示例#20
0
 def __init__(self, folder=None):
     self.folder = folder
     if self.folder is None:
         module = importlib.import_module(self.__class__.__module__)
         self.folder = os.path.dirname(module.__file__)
     self.jinja_env = Environment(
         loader=FunctionLoader(self._load_template),
         undefined=StrictUndefined,
     )
     self.init_variables()
示例#21
0
    def get_environment(cls):
        """
        Create and return a jinja environment to render templates

        Downstream modules can override this method to easily make changes
        to environment
        """
        env = Environment(loader=FunctionLoader(cls.jinja_loader_func))
        env.filters.update(cls.get_jinja_filters())
        return env
示例#22
0
    def __init__(self,
                 base='.',
                 variables={},
                 func_file=[],
                 filter_file=[],
                 debug=False):
        """constructor
        @base: directory path where to search for templates
        @variables: dictionary of variables for templates
        @func_file: file path to load functions from
        @filter_file: file path to load filters from
        @debug: enable debug
        """
        self.base = base.rstrip(os.sep)
        self.debug = debug
        self.log = Logger()
        self.variables = {}
        loader1 = FileSystemLoader(self.base)
        loader2 = FunctionLoader(self._template_loader)
        loader = ChoiceLoader([loader1, loader2])
        self.env = Environment(loader=loader,
                               trim_blocks=True,
                               lstrip_blocks=True,
                               keep_trailing_newline=True,
                               block_start_string=BLOCK_START,
                               block_end_string=BLOCK_END,
                               variable_start_string=VAR_START,
                               variable_end_string=VAR_END,
                               comment_start_string=COMMENT_START,
                               comment_end_string=COMMENT_END,
                               undefined=StrictUndefined)

        # adding variables
        self.variables['env'] = os.environ
        if variables:
            self.variables.update(variables)

        # adding header method
        self.env.globals['header'] = self._header
        # adding helper methods
        if self.debug:
            self.log.dbg('load global functions:')
        self._load_funcs_to_dic(jhelpers, self.env.globals)
        if func_file:
            for f in func_file:
                if self.debug:
                    self.log.dbg('load custom functions from {}'.format(f))
                self._load_path_to_dic(f, self.env.globals)
        if filter_file:
            for f in filter_file:
                if self.debug:
                    self.log.dbg('load custom filters from {}'.format(f))
                self._load_path_to_dic(f, self.env.filters)
        if self.debug:
            self._debug_dict('template additional variables', variables)
示例#23
0
 def prepare(self, filters=None, tests=None, globals={}, **kwargs):
     from jinja2 import Environment, FunctionLoader
     if 'prefix' in kwargs: # TODO: to be removed after a while
         raise RuntimeError('The keyword argument `prefix` has been removed. '
             'Use the full jinja2 environment name line_statement_prefix instead.')
     self.env = Environment(loader=FunctionLoader(self.loader), **kwargs)
     if filters: self.env.filters.update(filters)
     if tests: self.env.tests.update(tests)
     if globals: self.env.globals.update(globals)
     if self.source:
         self.tpl = self.env.from_string(self.source)
     else:
         self.tpl = self.env.get_template(self.filename)
示例#24
0
    def get_jinja_config(self, opt, template=None):
        def load_template(path):
            if os.path.exists(path):
                return open(path).read()

        loader = ChoiceLoader([
            FunctionLoader(load_template),
            PackageLoader('isotoma.recipe.apache', 'templates'),
        ])

        template = Environment(loader=loader).get_template(
            template or self.options['template'])
        return template.render(opt)
示例#25
0
    def get_lims_environment(cls):
        extensions = [
            'jinja2.ext.i18n', 'jinja2.ext.autoescape', 'jinja2.ext.with_',
            'jinja2.ext.loopcontrols', 'jinja2.ext.do'
        ]
        env = Environment(extensions=extensions,
                          loader=FunctionLoader(lambda name: ''))

        env.filters.update(cls.get_lims_filters())

        locale = Transaction().context.get('locale').split('_')[0]
        translations = TemplateTranslations(locale)
        env.install_gettext_translations(translations)
        return env
示例#26
0
    def get_environment(cls):
        """
        Create and return a jinja environment to render templates

        Downstream modules can override this method to easily make changes
        to environment
        """
        env = Environment(
            loader=FunctionLoader(cls.jinja_loader_func),
            autoescape=select_autoescape(['html', 'xml']),
            extensions=['jinja2.ext.loopcontrols'],
        )
        env.filters.update(cls.get_jinja_filters())
        return env
示例#27
0
    def render(self, level=1, hist=None, template=None):
        if template is None: template = self.kind

        def load(kind):
            temp = Bunch.resolve(
                TEMPLATES + kind + ".template", "template",
                "{% autoescape false %}{{ bunch.bunch }}{% endautoescape %}")
            return temp.bunch

        env = Environment(autoescape=True,
                          loader=FunctionLoader(load),
                          extensions=['jinja2.ext.autoescape'])
        return env.get_template(template).render(bunch=self,
                                                 level=level - 1,
                                                 template=template)
示例#28
0
def create_credentials_file(name, workspace="default"):
    ("""Create the credentials file.  It is JSON formatted""")
    # check that a default workspace was supplied for this user
    if workspace == "default":
        raise Exception(
            "A default workspace was not supplied for User {}".format(name))
    # form the config file name
    jdma_user_config_filename = os.environ["HOME"] + "/" + ".jdma.json"
    if not os.path.exists(jdma_user_config_filename):
        env = Environment(loader=FunctionLoader(load_template_from_url))
        template = env.get_template(settings.JDMA_CONFIG_URL)
        with open(jdma_user_config_filename, 'w') as fh:
            fh.write(
                template.render(et_user='******'.format(name),
                                default_storage='"elastictape"',
                                default_gws='"{}"'.format(workspace)))
示例#29
0
def build():
    """
    Build NML Python module from specification.
    """
    # Gather data
    exceptions = OrderedDict()
    for cls in NML_SPEC['classes']:
        for rel in cls['relations']:
            exc_name = 'Relation{}Error'.format(filter_objectize(rel['name']))
            exc_doc = (
                'A {} relation must relate with objects of type {}'.format(
                    rel['name'],
                    ' or '.join(filter_objectize(w) for w in rel['with'])))
            exceptions[exc_name] = exc_doc

    def lower_first(string):
        return string[:1].lower() + string[1:] if string else ''

    for cls in NML_SPEC['classes']:
        for attr in cls['attributes']:
            if attr['validation'] is not None:
                exc_name = 'Attribute{}Error'.format(
                    filter_objectize(attr['nml_attribute']))
                exceptions[exc_name] = 'Attribute `{}` must be a {}'.format(
                    attr['name'], lower_first(attr['doc']))

    # Build template environment
    def load_template(name):
        templates = {'nml': NML_TEMPLATE, 'exceptions': EXCEPTIONS_TEMPLATE}
        return templates[name]

    env = Environment(loader=FunctionLoader(load_template),
                      undefined=StrictUndefined)
    for ftr in ['objectize', 'methodize', 'variablize', 'pluralize']:
        env.filters[ftr] = globals()['filter_' + ftr]

    for tpl in ['nml', 'exceptions']:

        # Render template
        template = env.get_template(tpl)
        rendered = template.render(spec=NML_SPEC, exceptions=exceptions)

        # Write output
        root = dirname(normpath(abspath(__file__)))

        with open(join(root, '{}.py'.format(tpl)), 'w') as module:
            module.write(rendered)
    def patch_templates(self):
        """Patch page templates to add Hub-related buttons"""
        env = self.web_app.settings['jinja2_env']

        env.globals['hub_control_panel_url'] = \
            url_path_join(self.hub_prefix, 'home')

        # patch jinja env loading to modify page template
        def get_page(name):
            if name == 'page.html':
                return page_template

        orig_loader = env.loader
        env.loader = ChoiceLoader([
            FunctionLoader(get_page),
            orig_loader,
        ])