本文整理汇总了Python中template.Template类的典型用法代码示例。如果您正苦于以下问题:Python Template类的具体用法?Python Template怎么用?Python Template使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Template类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: writeVhost
def writeVhost(settings, domain, templateName, values):
"""Writes a site's vhost configuration file"""
# Open the file
conf = str(os.path.join(settings['confdir'], domain))
outFile = open(conf, 'w')
# Write the configuration
t = Template()
try:
tplDir = os.path.join(settings['templates'], templateName)
templateFilename = os.path.join(tplDir, templateName + '.tpl')
inFile = open(templateFilename, 'r')
source = inFile.read()
# While there are variables left unprocessed, process the string
expression = r'\[\%.+\%\]'
while re.search(expression, source) != None:
source = t.processString(source, values)
# Write what we have
outFile.write(source)
except TemplateException, e:
print "ERROR: %s" % e
示例2: testCompile
def testCompile(self):
ttcfg = { "POST_CHOMP": 1,
"INCLUDE_PATH": "test/src",
"COMPILE_EXT": ".ttc" }
# Check that compiled template files exist.
compiled = "test/src/foo.ttc"
self.assert_(os.path.exists(compiled))
self.assert_(os.path.exists("test/src/complex.ttc"))
# Ensure template metadata is saved in compiled file.
output = Template(ttcfg).process("baz", { "showname": 1 })
self.assertNotEqual(-1, output.find("name: baz"))
# We're going to hack on the foo.ttc file to change some key text.
# This way we can tell that the template was loaded from the compiled
# version and not the source.
fh = open(compiled, "r+")
stat = os.fstat(fh.fileno())
foo = fh.read()
fh.seek(0)
fh.write(foo.replace("the foo file", "the hacked foo file"))
fh.close()
os.utime(compiled, (stat.st_atime, stat.st_mtime))
self.Expect(DATA, ttcfg)
示例3: testContext
def testContext(self):
tt = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
'TRIM': True,
'POST_CHOMP': 1 })
ttpython = Template({ 'INCLUDE_PATH': 'test/src:test/lib',
'TRIM': True,
'POST_CHOMP': 1,
'EVAL_PYTHON': True })
ctx = tt.service().context()
self.failUnless(ctx)
self.assertEquals(ctx, tt.context())
self.failUnless(ctx.trim())
self.failUnless(not ctx.eval_python())
ctx = ttpython.service().context()
self.failUnless(ctx)
self.failUnless(ctx.trim())
self.failUnless(ctx.eval_python())
# template()
# Test that we can fetch a template via template()
tmpl = ctx.template('header')
self.failUnless(tmpl)
self.failUnless(isinstance(tmpl, Document))
# Test that non-existence of a template is reported
error = None
try:
tmpl = ctx.template('no_such_template')
except Exception, e:
error = e
示例4: testInclude
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)
示例5: create_user
def create_user(ldap_server, user):
old_user = find_user(ldap_server, config, user['USER_NAME'])
if old_user is None:
user['USER_ID'] = str(get_free_user_id(ldap_server))
user['USER_UID'] = str(uuid.uuid4())
else:
user['USER_ID'] = old_user['uidNumber'][0]
user['USER_UID'] = old_user['apple-generateduid'][0]
group = find_group(l, config, user['USER_GROUP_NAME'])
user['USER_GROUP_ID'] = group['gidNumber'][0]
user['USER_PASSWORD_HASH'] = "{KERBEROS} " + user['USER_NAME']
t = Template("../../config/plab-ldap/templates/user.ldif")
t.replace(config)
t.replace(user)
insert_ldif(ldap_server, str(t))
add_to_group(ldap_server, config, user['USER_NAME'], user['USER_GROUP_NAME'])
# Get user and show details
group = find_group(ldap_server, config, user['USER_GROUP_NAME'])
user = find_user(ldap_server, config, user['USER_NAME'])
pp = pprint.PrettyPrinter(indent = 4)
print "Added user (" + user['uid'][0] + ") with id (" + str(user['uidNumber']) + ")"
示例6: make_admin_staff_panel
def make_admin_staff_panel(self):
session = model.Session()
table = model.account
sql = table.select().order_by(table.c.account.asc(), table.c.username.asc())
query = session.execute(sql)
users = [dict(row.items()) for row in query]
rowtype = 1
for row in users:
# Alternate between values 1 and 2.
rowtype ^= 0x3
row["rowtype"] = rowtype
# Get latest action from DB.
action_table = model.activity
action_grab_sql = (
action_table.select()
.where(action_table.c.username == row["username"])
.order_by(action_table.c.date.desc())
)
last_action = session.execute(action_grab_sql).fetchone()
# Copy to row.
if last_action:
row["action"] = last_action["action"]
row["actiondate"] = last_action["date"]
else:
row["action"] = None
row["actiondate"] = None
Template.__init__(self, "staff_management", users=users)
示例7: generate
def generate(self):
print("=== Generating mocks for %s" % self.header_file)
cwd_stored = os.getcwd()
scriptdir = os.path.dirname(os.path.realpath(__file__))
print("Parsing file...")
os.chdir(self.tempdir)
fdv = FuncDeclVisitor(self.args)
fdv.parse(os.path.realpath(self.header_prep))
if self.args.print_ast:
# pprint(v.funcdecls)
fdv.ast.show(attrnames=True, nodenames=True)
if fdv.funcdecls:
HFile = collections.namedtuple(
'File', ['name', 'incl', 'funcs'])
file = HFile(name=self.header_name,
incl=self.header_file,
funcs=fdv.funcdecls)
os.chdir(scriptdir + "/../tmpl")
print("Generating %s" % (self.filemock_h))
self.mockh = Template("file.h.tmpl")
self.mockh.render({'file': file})
print("Generating %s" % (self.filemock_c))
self.mockc = Template("file.c.tmpl")
self.mockc.render({'file': file})
else:
print("No function declarations found in %s" % (self.header_file))
# restore cwd
os.chdir(cwd_stored)
示例8: generate
def generate(self, section=None):
if section is None:
section = self.navigation.root
t = Template(self, section)
t.generate()
for child in section.childs:
self.generate(child)
示例9: _generate
def _generate(self, path=None, output=None):
if not output:
output = self.args.output
if not path:
path = self.args.template
template = Template(path=path, output=output,
seed=self.args.seed, quiet=self.args.quiet)
template.generate()
示例10: testError
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())
示例11: make_admin_post_search_panel
def make_admin_post_search_panel(self, search, text, caller='internal'):
board = self.board
session = model.Session()
table = board.table
board.check_access(self.user)
popup = caller != 'board'
if search.find('IP Address') != -1:
try:
sql = table.select()\
.where(table.c.ip == misc.dot_to_dec(text))
except ValueError:
raise WakaError('Please enter a valid IP.')
search_type = 'IP'
elif search.find('Text String') != -1:
sql = table.select().where(table.c.comment.like('%'+text+'%'))
search_type = 'text string'
elif search.find('Author') != -1:
sql = table.select().where(or_(table.c.name.like('%'+text+'%'),
table.c.trip.like('%'+text+'%')))
search_type = 'author'
else:
sql = table.select().where(table.c.num == text)
search_type = 'ID'
if search_type != 'ID':
page = model.Page(sql, self.page, self.perpage)
rowcount = page.total_entries
total_pages = page.total_pages
posts = page.rows
if not posts:
raise WakaError("No posts found for %s %s" % (search_type, text))
else:
rowcount = total_pages = 1
row = session.execute(sql).fetchone()
if not row:
raise WakaError("Post not found. (It may have just been"
" deleted.)")
posts = [row]
inputs = [
{'name': 'board', 'value': board.name},
{'name' : 'task', 'value' : 'searchposts'},
{'name' : 'text', 'value' : text},
{'name': 'caller', 'value': caller},
{'name' : 'search', 'value': search}
]
rooturl = misc.make_script_url(task='searchposts', board=board.name,
caller=caller, search=search, text=text, _amp=True)
Template.__init__(self, 'post_search', num=id,
posts=posts, search=search, text=text,
inputs=inputs, number_of_pages=total_pages,
rooturl=rooturl, rowcount=rowcount, popup=popup)
示例12: make_edit_staff_window
def make_edit_staff_window(self, username):
boards = interboard.get_all_boards()
edited_user = staff.StaffMember.get(username)
for board in boards:
if board in edited_user.reign:
board["underpower"] = True
Template.__init__(self, "staff_edit_template", user_to_edit=username, boards=boards)
示例13: Expect
def Expect(self, data, tproc=None, vars=None):
vars = vars or {}
data = re.sub(r"(?m)^#.*\n", "", data)
match = re.search(r"\s*--\s*start\s*--\s*", data)
if match:
data = data[match.end():]
match = re.search(r"\s*--\s*stop\s*--\s*", data)
if match:
data = data[:match.start()]
tests = re.split(r"(?mi)^\s*--\s*test\s*--\s*", data)
if not tests[0]:
tests.pop(0)
ttprocs = None
if isinstance(tproc, dict):
tproc = Template(tproc)
elif isinstance(tproc, (tuple, list)):
ttprocs = dict(tproc)
tproc = tproc[0][1]
elif not isinstance(tproc, Template):
tproc = Template()
for count, test in enumerate(tests):
match = re.search(r"(?mi)^\s*-- name:? (.*?) --\s*\n", test)
if match:
name = match.group(1)
test = test[:match.start()] + test[match.end():]
else:
name = "template text %d" % (count + 1)
match = re.search(r"(?mi)^\s*--\s*expect\s*--\s*\n", test)
if match:
input, expect = test[:match.start()], test[match.end():]
else:
input, expect = test, ""
match = re.match(r"(?mi)^\s*--\s*use\s+(\S+)\s*--\s*\n", input)
if match:
ttname = match.group(1)
ttlookup = ttprocs.get(ttname)
if ttlookup:
tproc = ttlookup
else:
self.fail("no such template object to use: %s\n" % ttname)
input = input[:match.start()] + input[match.end():]
try:
out = tproc.processString(input, vars)
except Exception, e:
self.fail("Test #%d: %s process FAILED: %s\n%s" % (
count + 1, name, subtext(input), e))
match = re.match(r"(?i)\s*--+\s*process\s*--+\s*\n", expect)
if match:
expect = expect[match.end():]
try:
expect = tproc.processString(expect, vars)
except TemplateException, e:
self.fail("Test #%d: Template process failed (expect): %s" % (
count + 1, e))
示例14: count_templates
def count_templates(self):
"""
Retrieve count of existing templates created by owner of API-key
API call used is v1/template (GET)
@return: Integer
"""
temp_template = Template(api_client=self.api_client)
return temp_template.count()
示例15: testView
def testView(self):
vars = {"foo": Foo(pi=3.14, e=2.718), "blessed_list": MyList("Hello", "World")}
t = Template()
context = t.context()
view = context.view()
self.assert_(view)
view = context.view({"prefix": "my"})
self.assert_(view)
self.assertEquals("my", view.prefix())
self.Expect(DATA, None, vars)