Python jinja2.environment 模块,Environment() 实例源码

我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用jinja2.environment.Environment()

项目:geekcloud    作者:Mr-Linus    | 项目源码 | 文件源码
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
    with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
    # with open(script_path) as scriptf:
        with open(time_file_path) as timef:
            timing = getTiming(timef)
            json = scriptToJSON(scriptf, timing)

    fsl = FileSystemLoader(dirname(templatename), 'utf-8')
    e = Environment()
    e.loader = fsl

    templatename = basename(templatename)
    rendered = e.get_template(templatename).render(json=json,
                                                   dimensions=dimensions)

    return rendered
项目:geekcloud    作者:GeekCloud-Team    | 项目源码 | 文件源码
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
    with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
    # with open(script_path) as scriptf:
        with open(time_file_path) as timef:
            timing = getTiming(timef)
            json = scriptToJSON(scriptf, timing)

    fsl = FileSystemLoader(dirname(templatename), 'utf-8')
    e = Environment()
    e.loader = fsl

    templatename = basename(templatename)
    rendered = e.get_template(templatename).render(json=json,
                                                   dimensions=dimensions)

    return rendered
项目:server    作者:sgr-smile2015    | 项目源码 | 文件源码
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
    with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
    # with open(script_path) as scriptf:
        with open(time_file_path) as timef:
            timing = getTiming(timef)
            json = scriptToJSON(scriptf, timing)

    fsl = FileSystemLoader(dirname(templatename), 'utf-8')
    e = Environment()
    e.loader = fsl

    templatename = basename(templatename)
    rendered = e.get_template(templatename).render(json=json,
                                                   dimensions=dimensions)

    return rendered
项目:jumpsever    作者:jacksonyoudi    | 项目源码 | 文件源码
def renderTemplate(script_path, time_file_path, dimensions=(24, 80), templatename=DEFAULT_TEMPLATE):
    with copen(script_path, encoding='utf-8', errors='replace', newline='\r\n') as scriptf:
    # with open(script_path) as scriptf:
        with open(time_file_path) as timef:
            timing = getTiming(timef)
            json = scriptToJSON(scriptf, timing)

    fsl = FileSystemLoader(dirname(templatename), 'utf-8')
    e = Environment()
    e.loader = fsl

    templatename = basename(templatename)
    rendered = e.get_template(templatename).render(json=json,
                                                   dimensions=dimensions)

    return rendered
项目:muon    作者:pcastellazzi    | 项目源码 | 文件源码
def __init__(self, context):
        common_options = {
            'keep_trailing_newline': True,
        }

        cwd_loader = FileSystemLoader(os.getcwd())
        self._cwd_template = Environment(loader=cwd_loader, **common_options).get_template

        pkg_loader = PackageLoader('muon', 'templates')
        self._pkg_template = Environment(loader=pkg_loader, **common_options).get_template

        self._context = context
项目:Tuckshop    作者:MatthewJohn    | 项目源码 | 文件源码
def processTemplate(self):
        # Obtain template object
        env = Environment()
        env.loader = FileSystemLoader('./templates/')
        template = env.get_template('%s.html' % self.template)
        self.return_vars['page_object'] = self
        self.request_handler.wfile.write(unicode(template.render(**self.return_vars)).encode('latin1'))
项目:ndeploy    作者:sglebs    | 项目源码 | 文件源码
def templated_file_contents(options, configfile):
    paths = options["searchpath"].split(",") # CSV of PATHs
    if os.path.isdir(paths[0]):
        loader = FileSystemLoader(paths)
    else:
        loader = URLloader(paths)
    env = Environment(loader=loader)
    contents, config_full_path, _a_lambda_ = loader.get_source(env, configfile)
    template = env.from_string(contents, globals=options)
    return template.render(options)
项目:ndeploy    作者:sglebs    | 项目源码 | 文件源码
def templated_file_contents(config_as_dict, file_path):
    if os.path.exists(file_path):
        env = Environment()
        env.loader = FileSystemLoader(os.path.dirname(file_path))
        template = env.get_template(os.path.basename(file_path))
        return template.render(config_as_dict)
    else:
        return ""
项目:pizza-auth    作者:xxpizzaxx    | 项目源码 | 文件源码
def __init__(self, config, loader):
        self.config = config
        self.env = Environment()
        self.env.loader = loader
项目:Snakepit    作者:K4lium    | 项目源码 | 文件源码
def run(self, results, objfile):
        dumpdir = self.options.get("dumpdir", None)

        if not dumpdir:
            raise Exception("dumpdir not configured, skip")

        try:
            if not os.path.exists(dumpdir):
                os.makedirs(dumpdir)  
            d = tempfile.mkdtemp(dir=dumpdir)
        except Exception as e:
            raise Exception('Could not open %s for writing (%s)', dumpdir, e)
        else:
            os.rmdir(d)

            url_md5 = results["Info"]["url"]["md5"]
            file_md5 = results["Info"]["file"]["md5"]
            jfile = url_md5 + "_" + file_md5 + ".html"

            if not os.path.exists(dumpdir + jfile):
                try:
                    env = Environment(autoescape=True)
                    env.loader = FileSystemLoader(os.path.join(RAGPICKER_ROOT, "data", "html"))
                    template = env.get_template("report.html")
                    reporthtml = template.render({"results" : results})
                except UnicodeDecodeError:
                    reporthtml = template.render({"results" : convertDirtyDict2ASCII(results)})
                except Exception as e:
                    raise Exception("Failed to generate HTML report: %s" % e)

                try:
                    reportfile = codecs.open(os.path.join(dumpdir, jfile), "w", "utf-8")
                    reportfile.write(reporthtml)
                    reportfile.close()
                except (TypeError, IOError) as e:
                    raise Exception("Failed to write HTML report: %s" % e)
项目:software-factory    作者:softwarefactory-project    | 项目源码 | 文件源码
def render_template(dest, template, data):
    with open(dest, "w") as out:
        loader = FileSystemLoader(os.path.dirname(template))
        env = Environment(trim_blocks=True, loader=loader)
        template = env.get_template(os.path.basename(template))
        out.write("%s\n" % template.render(data))
    print("[+] Created %s" % dest)
项目:software-factory    作者:softwarefactory-project    | 项目源码 | 文件源码
def render_template(dest, template, data):
    with open(dest, "w") as out:
        loader = FileSystemLoader(os.path.dirname(template))
        env = Environment(trim_blocks=True, loader=loader)
        template = env.get_template(os.path.basename(template))
        out.write("%s\n" % template.render(data))
    print("[+] Created %s" % dest)
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def run(self, results):
        """Writes report.
        @param results: Cuckoo results dict.
        @raise CuckooReportError: if fails to write report.
        """
        if not HAVE_JINJA2:
            raise CuckooReportError("Failed to generate HTML report: "
                                    "Jinja2 Python library is not installed")

        shots_path = os.path.join(self.analysis_path, "shots")
        if os.path.exists(shots_path):
            shots = []
            counter = 1
            for shot_name in os.listdir(shots_path):
                if not shot_name.endswith(".jpg"):
                    continue

                shot_path = os.path.join(shots_path, shot_name)

                if os.path.getsize(shot_path) == 0:
                    continue

                shot = {}
                shot["id"] = os.path.splitext(File(shot_path).get_name())[0]
                shot["data"] = base64.b64encode(open(shot_path, "rb").read())
                shots.append(shot)

                counter += 1

            shots.sort(key=lambda shot: shot["id"])
            results["shots"] = shots
        else:
            results["shots"] = []

        env = Environment(autoescape=True)
        env.loader = FileSystemLoader(os.path.join(CUCKOO_ROOT,
                                                   "data", "html"))

        try:
            tpl = env.get_template("report.html")
            html = tpl.render({"results": results, "summary_report" : False})
        except UndefinedError as e:
            raise CuckooReportError("Failed to generate summary HTML report: {} ".format(e))
        except TemplateNotFound as e:
            raise CuckooReportError("Failed to generate summary HTML report: {} {} ".format(e, e.name))
        except (TemplateSyntaxError, TemplateAssertionError) as e:
            raise CuckooReportError("Failed to generate summary HTML report: {} on {}, line {} ".format(e, e.name,
                                                                                                        e.lineno))
        try:
            with codecs.open(os.path.join(self.reports_path, "report.html"), "w", encoding="utf-8") as report:
                report.write(html)
        except (TypeError, IOError) as e:
            raise CuckooReportError("Failed to write HTML report: %s" % e)

        return True