本文整理匯總了Python中jinja2.FileSystemLoader方法的典型用法代碼示例。如果您正苦於以下問題:Python jinja2.FileSystemLoader方法的具體用法?Python jinja2.FileSystemLoader怎麽用?Python jinja2.FileSystemLoader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2
的用法示例。
在下文中一共展示了jinja2.FileSystemLoader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: render_publications
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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
示例2: __init__
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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
}),
])
示例3: __init__
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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)
示例4: __init__
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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
示例5: load_plugins
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def load_plugins(self, plugins):
def trim(p):
if p.startswith('.'):
return False
return True
async def load(p):
plugin = Plugin(name=p)
if plugin.load_plugin():
await self.get_service('data_svc').store(plugin)
if plugin.name in self.get_config('plugins'):
await plugin.enable(self.get_services())
self.log.debug('Enabled plugin: %s' % plugin.name)
if not plugin.version:
self._errors.append(Error(plugin.name, 'plugin code is not a release version'))
for plug in filter(trim, plugins):
if not os.path.isdir('plugins/%s' % plug) or not os.path.isfile('plugins/%s/hook.py' % plug):
self.log.error('Problem locating the "%s" plugin. Ensure code base was cloned recursively.' % plug)
exit(0)
asyncio.get_event_loop().create_task(load(plug))
templates = ['plugins/%s/templates' % p.lower() for p in self.get_config('plugins')]
templates.append('templates')
aiohttp_jinja2.setup(self.application, loader=jinja2.FileSystemLoader(templates))
示例6: __make_report_supervised
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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()
示例7: generate_module_sample
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [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()
示例8: generate_file_jinja
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def generate_file_jinja(from_path, to_path, variables):
from_path_dir, from_path_filename = split(from_path)
loader = jinja2.FileSystemLoader(searchpath=from_path_dir)
env_parameters = dict(
loader=loader,
# some files like udev rules want empty lines at the end
# trim_blocks=True,
# lstrip_blocks=True,
undefined=jinja2.StrictUndefined
)
environment = jinja2.Environment(**env_parameters)
template = environment.get_template(from_path_filename)
output = template.render(variables)
to_path_dir = dirname(to_path)
if not isdir(to_path_dir):
makedirs(to_path_dir)
with open(to_path, 'wb+') as fh:
fh.write(output.encode("UTF-8"))
示例9: generate_file_jinja
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def generate_file_jinja(from_path, to_path, variables, variable_tags=('{{', '}}')):
from_path_dir, from_path_filename = split(from_path)
loader = jinja2.FileSystemLoader(searchpath=from_path_dir)
variable_start_tag, variable_end_tag = variable_tags
env_parameters = dict(
loader=loader,
# some files like udev rules want empty lines at the end
# trim_blocks=True,
# lstrip_blocks=True,
undefined=jinja2.StrictUndefined,
variable_start_string=variable_start_tag,
variable_end_string=variable_end_tag
)
environment = jinja2.Environment(**env_parameters)
template = environment.get_template(from_path_filename)
output = template.render(variables)
to_path_dir = dirname(to_path)
if not isdir(to_path_dir):
makedirs(to_path_dir)
with open(to_path, 'wb+') as fh:
fh.write(output.encode("UTF-8"))
示例10: template_file
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def template_file(in_file_path, out_file_path, **kwargs):
"""
Templates the given file with the keyword arguments.
Args:
in_file_path: The path to the template
out_file_path: The path to output the templated file
**kwargs: Variables to use in templating
"""
env = Environment(
loader=FileSystemLoader(os.path.dirname(in_file_path)),
keep_trailing_newline=True,
)
template = env.get_template(os.path.basename(in_file_path))
output = template.render(**kwargs)
with open(out_file_path, "w") as f:
f.write(output)
示例11: app_with_mail
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def app_with_mail(app):
"""App with email test templates."""
app.register_blueprint(
Blueprint(
"invenio_app_ils_tests", __name__,
template_folder="templates"
)
)
# add extra test templates to the search app blueprint, to fake the
# existence of `invenio-theme` base templates.
test_templates_path = os.path.join(os.path.dirname(__file__), "templates")
enhanced_jinja_loader = jinja2.ChoiceLoader([
app.jinja_loader,
jinja2.FileSystemLoader(test_templates_path),
])
# override default app jinja_loader to add the new path
app.jinja_loader = enhanced_jinja_loader
yield app
示例12: create_email
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def create_email(address, subject, template_name, context, attachment_filenames):
templateLoader = jinja2.FileSystemLoader(searchpath="templates")
templateEnv = jinja2.Environment(loader=templateLoader)
html_template = templateEnv.get_template(template_name + ".html")
html_to_send = html_template.render(context)
content = Content("text/html", html_to_send)
support_email = Email("support@unpaywall.org", "Unpaywall Team")
to_email = Email(address)
email = Mail(support_email, subject, to_email, content)
personalization = Personalization()
personalization.add_to(to_email)
# personalization.add_to(support_email)
email.add_personalization(personalization)
logger.info((u'sending email "{}" to {}'.format(subject, address)))
for filename in attachment_filenames:
email = add_results_attachment(email, filename)
return email
示例13: configure_grpc_subscription
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def configure_grpc_subscription(netconf_handler, proc_subid, proc_triggertype, proc_period, proc_xpath, proc_dstaddr, proc_dstport, proc_srcaddr, proc_srcvrf):
file_loader = FileSystemLoader('templates')
env = Environment(loader=file_loader)
template = env.get_template('grpc_template.j2')
flow_record_payload = template.render(grpc_subid=proc_subid, grpc_trigger_type= proc_triggertype, grpc_period=proc_period, grpc_xpath=proc_xpath, grpc_dstaddr=proc_dstaddr, grpc_dstport=proc_dstport, grpc_srcaddr=proc_srcaddr, grpc_srcvrf=proc_srcvrf)
netconf_reply = xml.dom.minidom.parseString(str(netconf_handler.edit_config(flow_record_payload, target='running')))
print (netconf_reply.toprettyxml( indent = " " ))
if "<ok/>" in (netconf_reply.toprettyxml(indent = " ")):
return_val = True
else:
return_val = False
return return_val
示例14: render
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def render(template_path, context):
"""
Assuming a template at /some/path/my_tpl.html, containing:
Hello {{ firstname }} {{ lastname }}!
>> context = {
'firstname': 'John',
'lastname': 'Doe'
}
>> result = render('/some/path/my_tpl.html', context)
>> print(result)
Hello John Doe!
"""
path, filename = opath.split(template_path)
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path or './')
).get_template(filename).render(context)
示例15: install_netns_systemd_service
# 需要導入模塊: import jinja2 [as 別名]
# 或者: from jinja2 import FileSystemLoader [as 別名]
def install_netns_systemd_service():
os_utils = osutils.BaseOS.get_os_util()
flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
# mode 00644
mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
# TODO(bcafarel): implement this for other init systems
# netns handling depends on a separate unit file
netns_path = os.path.join(consts.SYSTEMD_DIR,
consts.AMP_NETNS_SVC_PREFIX + '.service')
jinja_env = jinja2.Environment(
autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(
os.path.realpath(__file__)
) + consts.AGENT_API_TEMPLATES))
if not os.path.exists(netns_path):
with os.fdopen(os.open(netns_path, flags, mode), 'w') as text_file:
text = jinja_env.get_template(
consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2').render(
amphora_nsname=consts.AMPHORA_NAMESPACE,
HasIFUPAll=os_utils.has_ifup_all())
text_file.write(text)