本文整理汇总了Python中template.Template.process方法的典型用法代码示例。如果您正苦于以下问题:Python Template.process方法的具体用法?Python Template.process怎么用?Python Template.process使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类template.Template
的用法示例。
在下文中一共展示了Template.process方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testError
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def testError(self):
tmpl = Template({ 'BLOCKS': { 'badinc': '[% INCLUDE nosuchfile %]' } })
try:
tmpl.process("badinc")
self.fail("Failed to raise exception")
except TemplateException, e:
self.assertEquals('file', e.type())
self.assertEquals('nosuchfile: not found', e.info())
示例2: testTemplate
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def testTemplate(self):
out = StringBuffer()
tt = Template({"INCLUDE_PATH": "test/src:test/lib", "OUTPUT": out})
tt.process("header")
self.assert_(out.get())
out.clear()
try:
tt.process("this_file_does_not_exist")
self.fail("exception not raised")
except TemplateException, e:
self.assertEquals("file", e.type())
self.assertEquals("this_file_does_not_exist: not found", e.info())
示例3: testInclude
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def testInclude(self):
callsign = self._callsign()
replace = { "a": callsign["a"],
"b": callsign["b"],
"c": { "d": callsign["d"],
"e": callsign["e"],
"f": { "g": callsign["g"],
"h": callsign["h"] } },
"r": callsign["r"],
"s": callsign["s"],
"t": callsign["t"] }
tproc = Template({ "INTERPOLATE": True,
"INCLUDE_PATH": "test/src:test/lib",
"TRIM": True,
"AUTO_RESET": False,
"DEFAULT": "default" })
incpath = [ "test/src", "/nowhere" ]
tt_reset = Template({ "INTERPOLATE": True,
"INCLUDE_PATH": incpath,
"TRIM": True,
"RECURSION": True,
"DEFAULT": "bad_default" })
incpath[1] = "test/lib"
replace["metaout"] = tproc.process("metadata", replace)
replace["metamod"] = os.stat("test/src/metadata").st_mtime
self.Expect(DATA, (('default', tproc), ('reset', tt_reset)), replace)
示例4: render_template
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def render_template(content, basename):
"""Render the template."""
try:
name = 'pan.tt'
template = Template({'INCLUDE_PATH': os.path.join(os.path.dirname(__file__), 'tt')})
output = template.process(name, {'content': content, 'basename': basename})
except TemplateException as e:
msg = "Failed to render template %s with data %s: %s." % (name, content, e)
logger.error(msg)
raise TemplateException('render', msg)
return output
示例5: testOutput
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def testOutput(self):
f1 = "foo.bar"
f2 = "foo.baz"
file1 = os.path.join("test", "tmp", f1)
file2 = os.path.join("test", "tmp", f2)
if os.path.exists(file1):
os.remove(file1)
if os.path.exists(file2):
os.remove(file2)
tt = Template({ "INCLUDE_PATH": "test/src:test/lib",
"OUTPUT_PATH": "test/tmp",
"OUTPUT": f2 })
tt.process("foo", self._callsign())
self.assert_(os.path.exists(file2))
out = open(file2).read()
self.assertEquals("This is the foo file, a is alpha", out)
os.remove(file2)
intercept = InterceptDebug()
Template.DEBUG = True
util.Debug = intercept
tt.process("foo", self._callsign(), { "binmode": 1 })
self.assert_(os.path.exists(file2))
self.assertEquals("set binmode\n", intercept.message)
MyTemplate.MESSAGE = "reset"
intercept.message = "reset"
tt.process("foo", self._callsign(), { "binmode": 1 })
self.assert_(os.path.exists(file2))
self.assertEquals("set binmode\n", intercept.message)
示例6: process_template
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def process_template(self, template_file, vars):
config = {
'ABSOLUTE' : 1,
'INCLUDE_PATH' : HTDOCS_ABS_TEMPLATE_PATH,
'INTERPOLATE' : 1,
'POST_CHOMP' : 1,
'EVAL_PYTHON' : 1,
#'PRE_PROCESS' : 'header'
}
template = Template(config)
return template.process(template_file, vars)
示例7: write_toc
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def write_toc(toc, location):
"""Write the toc to disk."""
try:
name = 'toc.tt'
template = Template({'INCLUDE_PATH': os.path.join(os.path.dirname(__file__), 'tt')})
tocfile = template.process(name, {'toc': toc})
except TemplateException as e:
msg = "Failed to render template %s with data %s: %s." % (name, toc, e)
logger.error(msg)
raise TemplateException('render', msg)
with open(os.path.join(location, "mkdocs.yml"), 'w') as fih:
fih.write(tocfile)
示例8: process
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def process(self, template, model, options=None):
renderer = Template(self.config)
data = renderer.process(template, model, options)
del(renderer)
return data
示例9: __init__
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
class Indexer:
def __init__(self, suite, sections, suites, flags, splitChapter=False, templatePathList=None,
extraData=None, overviewTmplNames=None, overviewCopyExts=('.css', 'htaccess')):
"""Initialize indexer with TestSuite `suite` toc data file
`tocDataPath` and additional template paths in list `templatePathList`.
The toc data file should be list of tab-separated records, one
per line, of each spec section's uri, number/letter, and title.
`splitChapter` selects a single page index if False, chapter
indicies if True.
`extraData` can be a dictionary whose data gets passed to the templates.
`overviewCopyExts` lists file extensions that should be found
and copied from the template path into the main build directory.
The default value is ['.css', 'htaccess'].
`overviewTemplateNames` lists template names that should be
processed from the template path into the main build directory.
The '.tmpl' extension, if any, is stripped from the output filename.
The default value is ['index.htm.tmpl', 'index.xht.tmpl', 'testinfo.data.tmpl']
"""
self.suite = suite
self.splitChapter = splitChapter
self.extraData = extraData
self.overviewCopyExtPat = re.compile('.*(%s)$' % '|'.join(overviewCopyExts))
self.overviewTmplNames = overviewTmplNames if overviewTmplNames is not None \
else ['index.htm.tmpl', 'index.xht.tmpl', 'testinfo.data.tmpl',
'implementation-report-TEMPLATE.data.tmpl']
# Initialize template engine
self.templatePath = [join(w3ctestlib.__path__[0], 'templates')]
if templatePathList:
self.templatePath.extend(templatePathList)
self.templatePath = [abspath(path) for path in self.templatePath]
self.tt = Template({
'INCLUDE_PATH': self.templatePath,
'ENCODING' : 'utf-8',
'PRE_CHOMP' : 1,
'POST_CHOMP' : 0,
})
# Load toc data
self.sections = {}
for uri, numstr, title in sections:
uri = intern(uri.encode('utf-8'))
uriKey = intern(self._normalizeScheme(uri))
numstr = escapeToNamedASCII(numstr)
title = escapeToNamedASCII(title) if title else None
self.sections[uriKey] = Section(uri, title, numstr)
self.suites = suites
self.flags = flags
# Initialize storage
self.errors = {}
self.contributors = {}
self.alltests = []
def _normalizeScheme(self, uri):
if (uri and uri.startswith('http:')):
return 'https:' + uri[5:]
return uri
def indexGroup(self, group):
for test in group.iterTests():
data = test.getMetadata()
if data: # Shallow copy for template output
data = dict(data)
data['file'] = '/'.join((group.name, test.relpath)) \
if group.name else test.relpath
if (data['scripttest']):
data['flags'].append(intern('script'))
self.alltests.append(data)
for uri in data['links']:
uri = self._normalizeScheme(uri)
uri = uri.replace(self._normalizeScheme(self.suite.draftroot), self._normalizeScheme(self.suite.specroot))
if self.sections.has_key(uri):
testlist = self.sections[uri].tests.append(data)
for credit in data['credits']:
self.contributors[credit[0]] = credit[1]
else:
self.errors[test.sourcepath] = test.errors
def __writeTemplate(self, template, data, outfile):
o = self.tt.process(template, data)
with open(outfile, 'w') as f:
f.write(o.encode('utf-8'))
def writeOverview(self, destDir, errorOut=sys.stderr, addTests=[]):
"""Write format-agnostic pages such as test suite overview pages,
test data files, and error reports.
Indexed errors are reported to errorOut, which must be either
an output handle such as sys.stderr, a tuple of
(template filename string, output filename string)
or None to suppress error output.
`addTests` is a list of additional test paths, relative to the
overview root; it is intended for indexing raw tests
"""
#.........这里部分代码省略.........
示例10: type
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
try:
try:
vars["protocol"] = self.app().protocol
except AttributeError:
pass
try:
vars["domain"] = self.app().canonical_domain
except AttributeError:
vars["domain"] = self.app().domain
except AttributeError:
pass
self.call("web.universal_variables", vars)
if type(filename) == unicode:
filename = filename.encode("utf-8")
try:
content = tpl_engine.process(filename, vars)
except TypeError as e:
raise TemplateException("security", unicode(e))
except ValueError as e:
raise TemplateException("security", unicode(e))
except ImportError as e:
raise TemplateException("security", unicode(e))
except MemoryError:
raise TemplateException("security", self._("Memory overflow during template processing"))
except TooManyLoops:
raise TemplateException("security", self._("Too many template loop iterations"))
except ZeroDivisionError:
raise TemplateException("security", self._("Zero division in the template"))
if req:
req.templates_len = req.templates_len + len(content)
m = re_content.match(content)
示例11: testProvider
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
def testProvider(self):
dir = "test/src"
lib = "test/lib"
file = "foo"
relfile = os.path.join(".", dir, file)
absfile = os.path.join(os.path.abspath(dir), file)
newfile = os.path.join(dir, "foobar")
def update_file(*args):
time.sleep(2) # ensure file time stamps are different
f = open(newfile, "w")
for arg in args:
f.write(str(arg))
f.close()
vars = { "file": file,
"relfile": relfile,
"absfile": absfile,
"fixfile": update_file }
update_file("This is the old content")
#------------------------------------------------------------------------
# instantiate a bunch of providers, using various different techniques,
# with different load options but sharing the same parser; then set them
# to work fetching some files and check they respond as expected
#------------------------------------------------------------------------
parser = Config.parser({"POST_CHOMP": 1})
provinc = Config.provider({ "INCLUDE_PATH": dir,
"PARSER": parser,
"TOLERANT": 1 })
provabs = Config.provider({ "ABSOLUTE": 1, "PARSER": parser })
provrel = Config.provider({ "RELATIVE": 1, "PARSER": parser })
self.assert_(provinc.parser() is provabs.parser())
self.assert_(provabs.parser() is provrel.parser())
self.assert_(delivered(provinc, file))
self.assert_(declined(provinc, absfile))
self.assert_(declined(provinc, relfile))
self.assert_(declined(provabs, file))
self.assert_(delivered(provabs, absfile))
self.assert_(denied(provabs, relfile))
self.assert_(declined(provrel, file))
self.assert_(denied(provrel, absfile))
self.assert_(delivered(provrel, relfile))
# Test if can fetch from a file handle.
ttfile = Template()
path = os.path.join(os.path.abspath(dir), "baz")
file = open(path)
outstr = ttfile.process(file, { "a": "filetest" })
file.close()
self.assertEquals("This is the baz file, a: filetest\n", outstr)
#------------------------------------------------------------------------
# now we'll fold those providers up into some Template objects that
# we can pass to text_expect() to do some template driven testing
#------------------------------------------------------------------------
ttinc = Template({ "LOAD_TEMPLATES": [provinc] })
ttabs = Template({ "LOAD_TEMPLATES": [provabs] })
ttrel = Template({ "LOAD_TEMPLATES": [provrel] })
def dpaths():
return [os.path.join(lib, x) for x in "one", "two"]
def badpaths():
return [badpaths]
ttd1 = Template({ "INCLUDE_PATH": [dpaths, dir], "PARSER": parser })
ttd2 = Template(
{ "INCLUDE_PATH": [DynamicPaths(os.path.join(lib, "two"),
os.path.join(lib, "one")), dir],
"PARSER": parser })
ttd3 = Template({ "INCLUDE_PATH": [ badpaths ], "PARSER": parser })
uselist = (("ttinc", ttinc),
("ttabs", ttabs),
("ttrel", ttrel),
("ttd1", ttd1),
("ttd2", ttd2),
("ttdbad", ttd3))
self.Expect(DATA, uselist, vars)
示例12: Template
# 需要导入模块: from template import Template [as 别名]
# 或者: from template.Template import process [as 别名]
from template import Template
from template.util import Literal
template = Template()
source = Literal("Hello [% name or 'World' %]!")
print template.process(source);
print template.process(source, {'name':'Badger'});