Python jinja2.Template() Examples

The following are 30 code examples of jinja2.Template(). 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: debug.py    From quart with MIT License 7 votes vote down vote up
def traceback_response() -> Response:
    type_, value, tb = sys.exc_info()
    frames = []
    while tb:
        frame = tb.tb_frame
        try:
            code = inspect.getsourcelines(frame)
        except OSError:
            code = None

        frames.append(
            {
                "file": inspect.getfile(frame),
                "line": frame.f_lineno,
                "locals": frame.f_locals,
                "code": code,
            }
        )
        tb = tb.tb_next

    name = type_.__name__
    template = Template(TEMPLATE)
    html = template.render(frames=reversed(frames), name=name, value=value)
    return Response(html, 500) 
Example #2
Source File: context.py    From mkdocs_macros_plugin with MIT License 6 votes vote down vote up
def make_html(rows, header=[], tb_class='pretty'):
    "Produce an HTML table"
    back_color = "#F0FFFF" # light blue
    grid_color = "#DCDCDC"
    padding = "5px"
    style = "border:1px solid %s; padding: %s" % (grid_color, padding)
    templ = Template("""
<table class="{{ tb_class }}" style="background-color: {{ back_color}}; {{ style }}">
    {% for item in header %}
    <th style="{{ style }}">{{ item }}</th>
    {% endfor %}
    {% for row in rows %}
        <tr>
        {% for item in row %}
            <td style="vertical-align:top; {{ style }}">{{ item }}</td>
        {% endfor %}
        </tr>
    {% endfor %}
</table>
    """)
    return templ.render(locals()) 
Example #3
Source File: util.py    From pyinfra with MIT License 6 votes vote down vote up
def get_template(filename_or_string, is_string=False):
    '''
    Gets a jinja2 ``Template`` object for the input filename or string, with caching
    based on the filename of the template, or the SHA1 of the input string.
    '''

    # Cache against string sha or just the filename
    cache_key = sha1_hash(filename_or_string) if is_string else filename_or_string

    if cache_key in TEMPLATES:
        return TEMPLATES[cache_key]

    if is_string:
        # Set the input string as our template
        template_string = filename_or_string

    else:
        # Load template data into memory
        with open(filename_or_string, 'r') as file_io:
            template_string = file_io.read()

    TEMPLATES[cache_key] = Template(template_string, keep_trailing_newline=True)
    return TEMPLATES[cache_key] 
Example #4
Source File: index.py    From modelforge with Apache License 2.0 6 votes vote down vote up
def load_template(self, template: str) -> Template:
        """Load a Jinja2 template from the source directory."""
        env = dict(trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False)
        jinja2_ext = ".jinja2"
        if not template.endswith(jinja2_ext):
            self._log.error("Template file name must end with %s" % jinja2_ext)
            raise ValueError
        if not template[:-len(jinja2_ext)].endswith(".md"):
            self._log.error("Template file should be a Markdown file")
            raise ValueError
        if not os.path.isabs(template):
            template = os.path.join(os.path.dirname(__file__), template)
        with open(template, encoding="utf-8") as fin:
            template_obj = Template(fin.read(), **env)
        template_obj.filename = template
        self._log.info("Loaded %s", template)
        return template_obj 
Example #5
Source File: index.py    From modelforge with Apache License 2.0 6 votes vote down vote up
def add_model(self, model_type: str, model_uuid: str, meta: dict,
                  template_model: Template, update_default: bool=False):
        """Add a new model to the registry. Call `upload()` to update the remote side."""
        if update_default or model_type not in self.meta:
            self.meta[model_type] = meta["default"]
        model_meta = meta["model"]
        self.models.setdefault(model_type, {})[model_uuid] = model_meta
        model_directory = os.path.join(self.cached_repo, model_type)
        os.makedirs(model_directory, exist_ok=True)
        model = os.path.join(model_directory, model_uuid + ".md")
        if os.path.exists(model):
            os.remove(model)
        links = {}
        for m_type, items in self.models.items():
            for uuid in items:
                if uuid in model_meta["dependencies"]:
                    links[uuid] = os.path.join("/", m_type, "%s.md" % uuid)
        with open(model, "w") as fout:
            fout.write(template_model.render(model_type=model_type, model_uuid=model_uuid,
                                             meta=model_meta, links=links, spdx=LICENSES))
        git.add(self.cached_repo, [model])
        self._log.info("Added %s", model) 
Example #6
Source File: detection_perf.py    From ctw-baseline with MIT License 6 votes vote down vote up
def html_explore(report):
    jdata = [{
        'model_name': 'YOLO_v2',
        'performance': {
            szname: {
                'attributes': [
                    {'n': o['n'], 'recalls': {1: o['recall']}} for o in szattr['attributes']
                ],
            } for szname, szattr in report['performance'].items()
        },
    }]
    with open('explore_cls.template.html') as f:
        template = Template(f.read())
    with codecs.open(settings.PROPOSAL_EXPLORE if proposal else settings.DETECTION_EXPLORE, 'w', 'utf-8') as f:
        f.write(template.render({
            'title': 'Explore detection performance',
            'chartjs': get_chartjs(),
            'performance_all': json.dumps(jdata, sort_keys=True),
            'attributes': settings.ATTRIBUTES,
        })) 
Example #7
Source File: charts.py    From whiskyton with MIT License 6 votes vote down vote up
def create(self):
        """
        This method creates a SVG chart.
        :return: (string) contents of the SVG file
        """

        # variables for drawing
        grid = self.__grid_coordinates()
        objs = {
            "grid": grid,
            "labels": self.__txt_coordinates(grid),
            "reference": self.area_coordinates(self.reference, grid),
            "whisky": self.area_coordinates(self.comparison, grid),
            "center_x": self.center_x,
            "center_y": self.center_y,
        }

        # generate the svg
        basedir = app.config["BASEDIR"]
        template = basedir.child("whiskyton", "templates", "chart.svg")
        with open(template, "r") as file_handler:

            # create SVG
            svg_template = Template(file_handler.read())
            return html_minify(svg_template.render(**objs), parser="xml") 
Example #8
Source File: workflow_generator.py    From gordo with GNU Affero General Public License v3.0 6 votes vote down vote up
def load_workflow_template(workflow_template: str) -> jinja2.Template:
    """
    Loads the Jinja2 Template from a specified path

    Parameters
    ----------
    workflow_template: str
        Path to a workflow template

    Returns
    -------
    jinja2.Template
        Loaded but non-rendered jinja2 template for the workflow
    """
    path_to_workflow_template = os.path.abspath(workflow_template)
    template_dir = os.path.dirname(path_to_workflow_template)

    templateEnv = jinja2.Environment(
        loader=jinja2.FileSystemLoader(template_dir), undefined=jinja2.StrictUndefined
    )
    return templateEnv.get_template(os.path.basename(workflow_template)) 
Example #9
Source File: tasks.py    From kartotherian_docker with Apache License 2.0 6 votes vote down vote up
def _run_sql_script(ctx, script_name, template_params=None):
    """
    Run SQL commands from a file over the import database.
    If `template_params` is not None, the file is interpreted as a Jinja
    template.
    """
    script_path = os.path.join(ctx.imposm_config_dir, script_name)

    with open(script_path, 'r') as f:
        sql_commands = f.read()

        if template_params is not None:
            sql_commands = (
                jinja2.Template(sql_commands).render(**template_params)
            )

        return _execute_sql(
            ctx,
            sql_commands,
            db=ctx.pg.import_database,
            additional_options="--set ON_ERROR_STOP='1'"
        ) 
Example #10
Source File: plot_directive.py    From Computable with MIT License 6 votes vote down vote up
def split_code_at_show(text):
    """
    Split code at plt.show()

    """

    parts = []
    is_doctest = contains_doctest(text)

    part = []
    for line in text.split("\n"):
        if (not is_doctest and line.strip() == 'plt.show()') or \
               (is_doctest and line.strip() == '>>> plt.show()'):
            part.append(line)
            parts.append("\n".join(part))
            part = []
        else:
            part.append(line)
    if "\n".join(part).strip():
        parts.append("\n".join(part))
    return parts

#------------------------------------------------------------------------------
# Template
#------------------------------------------------------------------------------ 
Example #11
Source File: plugin.py    From mkdocs-markdownextradata-plugin with MIT License 5 votes vote down vote up
def on_page_markdown(self, markdown, config, **kwargs):
        context = {key: config.get(key) for key in CONFIG_KEYS if key in config}
        context.update(config.get("extra", {}))
        md_template = Template(markdown)
        return md_template.render(**config.get("extra")) 
Example #12
Source File: flash_algo.py    From JMCUProg with MIT License 5 votes vote down vote up
def process_template(self, template_path, output_path, data_dict=None):
        ''' 用模板文件生成输出文件, 此类的所有数据都可以在模板中通过 'algo' 访问
            data_dict: 生成输出时模板需要的其他数据                        '''
        if data_dict is None: data_dict = {}
        
        assert 'algo' not in data_dict, 'algo already set by user data'
        data_dict['algo'] = self

        with open(template_path) as f:
            template = jinja2.Template(f.read())

            with open(output_path, 'wb') as f:
                f.write(template.render(data_dict).encode('latin')) 
Example #13
Source File: redismgmt.py    From monaco with MIT License 5 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger('monaco.RedisMgmt')
        self.lock = REDISMGMTLOCK
        with open(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'templates/redis.conf')) as template_file:
            self.template = jinja2.Template(template_file.read())


        self.TEMPLATED = ['port', 'rename-config', 'rename-shutdown']
        self.NOT_DYNAMIC = ['maxmemory']
        self.DYNAMIC = ['maxmemory-policy', 'save', 'slaveof', 'slave-read-only'] 
Example #14
Source File: application.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_template(self, filename):
        return Template(file(resource_filename('kotori.vendor.hiveeyes', filename)).read().decode('utf-8')) 
Example #15
Source File: application.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_template(self, filename):
        return Template(file(resource_filename('kotori.vendor.luftdaten', filename)).read().decode('utf-8')) 
Example #16
Source File: render.py    From financial_life with Apache License 2.0 5 votes vote down vote up
def render_accounts(simulation, template_folder, output_dir = 'report', accounts_folder = path_accounts):
    """ Renders for each account a detailed page with all account-specific
    data """
    accounts = simulation.accounts
    links = []
    
    # image folder for the account related pictures
    img_folder = output_dir + sl + accounts_folder + 'img' + sl
    if not os.path.exists(img_folder):
        os.makedirs(img_folder)    
    
    for (i, a) in enumerate(accounts):
        account_name = a.name
        account_name.replace(' ', '_')
        prefix = 'account_details_%03i_%s' % (i, account_name)
        account_link = accounts_folder + prefix + '.html'
        print('Render %s' % account_link)
        links.append(account_link)
        
        data = {}
        data['account_name'] = a.name
        data['tables'] = a.get_report_json(interval='all')
        data['backlink'] = '..' + sl + 'index.html'
        img_data = plt.summary_img(a.report.yearly(), target = img_folder, prefix = prefix)
        data.update(img_data) 
        
        template_file = 'account_details.html'
        with open(template_folder + sl + template_file, 'r') as f:
            content = f.read()
            t = Template(content)
            with open(output_dir + sl + account_link, 'w') as o:
                o.write(t.render(**data))
    return links 
Example #17
Source File: render.py    From financial_life with Apache License 2.0 5 votes vote down vote up
def render(simulation, output_dir = 'report'):
    print("Calling render function")
    template_folder = os.path.dirname(os.path.realpath(__file__))
    img_folder = output_dir + sl + path_img + sl
    accounts_folder = path_accounts + sl
    
    print('Template Folder: %s' % template_folder)
    # makedirs creates also all intermediate folders, therefore, we don't need
    # to create result_folder explicitely
    if not os.path.exists(img_folder):
        os.makedirs(img_folder)
    if not os.path.exists(output_dir + sl + accounts_folder):
        os.makedirs(output_dir + sl + accounts_folder)
            
    img_data = plt.summary_img(*simulation.reports('yearly'), target = img_folder)
    data = {}
    data['title'] = 'Kalkulation: ' + output_dir
    data['date'] = datetime.now().strftime("%d.%m.%Y - %H:%M:%S")
    
    data.update(img_data)
    data.update(simulation.get_payments_unique_json())
    data.update(simulation.get_payments_regular_json())
    
    accounts = simulation.get_accounts_json()
    links = render_accounts(simulation, template_folder, output_dir, accounts_folder)
    
    # get_accounts_json and render_accounts iterate through simulation.account
    # therefore, the order in both is equal and we can add the link to the 
    # accounts json. this is not the safest way but I did not wanted to put
    # the get_accounts_json routine into this render-function 
    for a, l in zip(accounts['accounts'], links):
        a['link'] = l
    data.update(accounts)
    
    index_file = "index.html"
    with open(template_folder + sl + index_file, 'r') as f:
        content = f.read()
        t = Template(content)
        with open(output_dir + sl + index_file, 'w') as o:
            o.write(t.render(**data)) 
Example #18
Source File: dashboard.py    From kotori with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_template(self, filename):
        filename = os.path.join('resources', filename)
        return Template(file(resource_filename('kotori.daq.graphing.grafana', filename)).read()) 
Example #19
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read(),
                        keep_trailing_newline=True,
                        lstrip_blocks=True,
                        trim_blocks=True)
        out_file.write(tmle.render(os.environ)) 
Example #20
Source File: utils.py    From koku with GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_template(self, provider_type, static_data_file):
        """Prepare the Jinja template for static data."""
        static_data = pkgutil.get_data("api.report.test", static_data_file)
        template = Template(static_data.decode("utf8"))
        static_data_path = f"/tmp/{provider_type}_static_data.yml"
        return template, static_data_path 
Example #21
Source File: templates.py    From foremast with Apache License 2.0 5 votes vote down vote up
def get_template_object(template_file=''):
    """Retrieve template.

    Args:
        template_file (str): Name of template file.

    Returns:
        jinja2.Template: Template ready to render.

    Raises:
        AssertionError: Configured path for templates does not exist.
        :obj:`foremast.exceptions.ForemastTemplateNotFound`: Requested template
            is not available.

    """
    jinja_template_paths_obj = []

    if TEMPLATES_PATH:
        external_templates = pathlib.Path(TEMPLATES_PATH).expanduser().resolve()
        assert os.path.isdir(external_templates), 'External template path "{0}" not found'.format(external_templates)
        jinja_template_paths_obj.append(external_templates)

    jinja_template_paths_obj.append(LOCAL_TEMPLATES)
    jinja_template_paths = [str(path) for path in jinja_template_paths_obj]

    jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader(jinja_template_paths))

    try:
        template = jinjaenv.get_template(template_file)
    except jinja2.TemplateNotFound:
        message = 'Unable to find template "{template_file}" in paths {paths}'.format(
            template_file=template_file, paths=jinjaenv.loader.searchpath)
        LOG.error(message)
        raise ForemastTemplateNotFound(message)

    return template 
Example #22
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        t = Template(in_file.read(),
                     keep_trailing_newline=True,
                     lstrip_blocks=True,
                     trim_blocks=True)
        out_file.write(t.render(os.environ)) 
Example #23
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read())
        out_file.write(tmle.render(os.environ)) 
Example #24
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read())
        out_file.write(tmle.render(os.environ)) 
Example #25
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read(),
                        keep_trailing_newline=True,
                        lstrip_blocks=True,
                        trim_blocks=True)
        out_file.write(tmle.render(os.environ)) 
Example #26
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        t = Template(in_file.read(),
                     keep_trailing_newline=True,
                     lstrip_blocks=True,
                     trim_blocks=True)
        out_file.write(t.render(os.environ)) 
Example #27
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read(),
                        keep_trailing_newline=True,
                        lstrip_blocks=True,
                        trim_blocks=True)
        out_file.write(tmle.render(os.environ)) 
Example #28
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read())
        out_file.write(tmle.render(os.environ)) 
Example #29
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        tmle = Template(in_file.read())
        out_file.write(tmle.render(os.environ)) 
Example #30
Source File: template.py    From monasca-docker with Apache License 2.0 5 votes vote down vote up
def main():
    if len(sys.argv) != 3:
        print('Usage: {} [input] [output]'.format(sys.argv[0]))
        sys.exit(1)

    in_path = sys.argv[1]
    out_path = sys.argv[2]

    with open(in_path, 'r') as in_file, open(out_path, 'w') as out_file:
        t = Template(in_file.read(),
                     keep_trailing_newline=True,
                     lstrip_blocks=True,
                     trim_blocks=True)
        out_file.write(t.render(os.environ))