本文整理汇总了Python中mako.template.Template方法的典型用法代码示例。如果您正苦于以下问题:Python template.Template方法的具体用法?Python template.Template怎么用?Python template.Template使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mako.template
的用法示例。
在下文中一共展示了template.Template方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
""" Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
"""
self.name = name
self.source = source.read() if hasattr(source, 'read') else source
self.filename = source.filename if hasattr(source, 'filename') else None
self.lookup = [os.path.abspath(x) for x in lookup]
self.encoding = encoding
self.settings = self.settings.copy() # Copy from class variable
self.settings.update(settings) # Apply
if not self.source and self.name:
self.filename = self.search(self.name, self.lookup)
if not self.filename:
raise TemplateError('Template %s not found.' % repr(name))
if not self.source and not self.filename:
raise TemplateError('No template specified.')
self.prepare(**self.settings)
示例2: template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
adapter = kwargs.pop('template_adapter', SimpleTemplate)
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
tplid = (id(lookup), tpl)
if tplid not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
if isinstance(tpl, adapter):
TEMPLATES[tplid] = tpl
if settings: TEMPLATES[tplid].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tplid]:
abort(500, 'Template (%s) not found' % tpl)
for dictarg in args[1:]: kwargs.update(dictarg)
return TEMPLATES[tplid].render(kwargs)
示例3: render
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def render(self, template_url, destination, variables, overwrite=False):
"""Render the provided template"""
if 'mako' not in sys.modules:
print(
f'{c.Fore.RED}Missing mako module. Try installing "pip install tcex[development]"'
)
sys.exit(1)
status = 'Failed'
if not os.path.isfile(destination) or overwrite:
template_data = self.download_template(template_url)
template = Template(template_data)
rendered_template = template.render(**variables)
with open(destination, 'w') as f:
f.write(rendered_template)
status = 'Success'
else:
status = 'Skipped'
self._template_render_results.append(
{'destination': destination, 'status': status, 'url': template_url}
)
示例4: __init__
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings):
""" Create a new template.
If the source parameter (str or buffer) is missing, the name argument
is used to guess a template filename. Subclasses can assume that
self.source and/or self.filename are set. Both are strings.
The lookup, encoding and settings parameters are stored as instance
variables.
The lookup parameter stores a list containing directory paths.
The encoding parameter should be used to decode byte strings or files.
The settings parameter contains a dict for engine-specific settings.
"""
self.name = name
self.source = source.read() if hasattr(source, 'read') else source
self.filename = source.filename if hasattr(source, 'filename') else None
self.lookup = map(os.path.abspath, lookup)
self.encoding = encoding
self.settings = self.settings.copy() # Copy from class variable
self.settings.update(settings) # Apply
if not self.source and self.name:
self.filename = self.search(self.name, self.lookup)
if not self.filename:
raise TemplateError('Template %s not found.' % repr(name))
if not self.source and not self.filename:
raise TemplateError('No template specified.')
self.prepare(**self.settings)
示例5: template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
template_adapter = kwargs.pop('template_adapter', SimpleTemplate)
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
if isinstance(tpl, template_adapter):
TEMPLATES[tpl] = tpl
if settings: TEMPLATES[tpl].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tpl]:
abort(500, 'Template (%s) not found' % tpl)
for dictarg in args[1:]: kwargs.update(dictarg)
return TEMPLATES[tpl].render(kwargs)
示例6: template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def template(*args, **kwargs):
"""
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
"""
tpl = args[0] if args else None
for dictarg in args[1:]:
kwargs.update(dictarg)
adapter = kwargs.pop('template_adapter', SimpleTemplate)
lookup = kwargs.pop('template_lookup', TEMPLATE_PATH)
tplid = (id(lookup), tpl)
if tplid not in TEMPLATES or DEBUG:
settings = kwargs.pop('template_settings', {})
if isinstance(tpl, adapter):
TEMPLATES[tplid] = tpl
if settings: TEMPLATES[tplid].prepare(**settings)
elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl:
TEMPLATES[tplid] = adapter(source=tpl, lookup=lookup, **settings)
else:
TEMPLATES[tplid] = adapter(name=tpl, lookup=lookup, **settings)
if not TEMPLATES[tplid]:
abort(500, 'Template (%s) not found' % tpl)
return TEMPLATES[tplid].render(kwargs)
示例7: write_server_config_template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def write_server_config_template(server_config, args):
# Load template
try:
template = Template(filename=args.server_config_template)
except IOError as err:
logging.error("Failed to load server config template. " + err.strerror)
sys.exit(3)
conf = template.render(
service_configs=args.service_configs,
management=args.management,
service_control_url_override=args.service_control_url_override,
rollout_id=args.rollout_id,
rollout_strategy=args.rollout_strategy,
always_print_primitive_fields=args.transcoding_always_print_primitive_fields,
client_ip_header=args.client_ip_header,
client_ip_position=args.client_ip_position,
rewrite_rules=args.rewrite,
disable_cloud_trace_auto_sampling=args.disable_cloud_trace_auto_sampling,
cloud_trace_url_override=args.cloud_trace_url_override)
# Save nginx conf
try:
f = open(server_config, 'w+')
f.write(conf)
f.close()
except IOError as err:
logging.error("Failed to save server config." + err.strerror)
sys.exit(3)
示例8: source
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def source(self):
"""Return the template source code for this :class:`.Template`."""
return _get_module_info_from_callable(self.callable_).source
示例9: code
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def code(self):
"""Return the module source code for this :class:`.Template`."""
return _get_module_info_from_callable(self.callable_).code
示例10: render_context
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def render_context(self, context, *args, **kwargs):
"""Render this :class:`.Template` with the given context.
The data is written to the context's buffer.
"""
if getattr(context, "_with_template", None) is None:
context._set_with_template(self)
runtime._render_context(self, self.callable_, context, *args, **kwargs)
示例11: has_template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def has_template(self, uri):
"""Return ``True`` if this :class:`.TemplateLookup` is
capable of returning a :class:`.Template` object for the
given ``uri``.
:param uri: String URI of the template to be resolved.
"""
try:
self.get_template(uri)
return True
except exceptions.TemplateLookupException:
return False
示例12: adjust_uri
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def adjust_uri(self, uri, filename):
"""Adjust the given ``uri`` based on the calling ``filename``.
When this method is called from the runtime, the
``filename`` parameter is taken directly to the ``filename``
attribute of the calling template. Therefore a custom
:class:`.TemplateCollection` subclass can place any string
identifier desired in the ``filename`` parameter of the
:class:`.Template` objects it constructs and have them come back
here.
"""
return uri
示例13: get_template
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def get_template(self, uri):
"""Return a :class:`.Template` object corresponding to the given
``uri``.
.. note:: The ``relativeto`` argument is not supported here at
the moment.
"""
try:
if self.filesystem_checks:
return self._check(uri, self._collection[uri])
else:
return self._collection[uri]
except KeyError:
u = re.sub(r"^\/+", "", uri)
for dir_ in self.directories:
# make sure the path seperators are posix - os.altsep is empty
# on POSIX and cannot be used.
dir_ = dir_.replace(os.path.sep, posixpath.sep)
srcfile = posixpath.normpath(posixpath.join(dir_, u))
if os.path.isfile(srcfile):
return self._load(srcfile, uri)
else:
raise exceptions.TopLevelLookupException(
"Cant locate template for uri %r" % uri
)
示例14: _load
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def _load(self, filename, uri):
self._mutex.acquire()
try:
try:
# try returning from collection one
# more time in case concurrent thread already loaded
return self._collection[uri]
except KeyError:
pass
try:
if self.modulename_callable is not None:
module_filename = self.modulename_callable(filename, uri)
else:
module_filename = None
self._collection[uri] = template = Template(
uri=uri,
filename=posixpath.normpath(filename),
lookup=self,
module_filename=module_filename,
**self.template_args
)
return template
except:
# if compilation fails etc, ensure
# template is removed from collection,
# re-raise
self._collection.pop(uri, None)
raise
finally:
self._mutex.release()
示例15: put_string
# 需要导入模块: from mako import template [as 别名]
# 或者: from mako.template import Template [as 别名]
def put_string(self, uri, text):
"""Place a new :class:`.Template` object into this
:class:`.TemplateLookup`, based on the given string of
``text``.
"""
self._collection[uri] = Template(
text, lookup=self, uri=uri, **self.template_args
)