本文整理汇总了Python中genshi.template.NewTextTemplate类的典型用法代码示例。如果您正苦于以下问题:Python NewTextTemplate类的具体用法?Python NewTextTemplate怎么用?Python NewTextTemplate使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NewTextTemplate类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _process_template
def _process_template(self, template_filename, **kwargs):
f = open(os.path.join(self.template_folder, template_filename))
template_text = f.read()
template = NewTextTemplate(template_text)
f.close()
stream = template.generate(**kwargs)
return stream.render()
示例2: __init__
def __init__(self, **kwargs):
"""
This is a genshi-based template mail renderer.
It derives from L{Message} and introduces three
additional keyword-args:
- "html" for a MarkupTemplate
- "text" for a TextTemplate
- "subject" for a TextTemplate to use for the subject
The templates are currently always loaded relative
to the package::
abl.devtools
"""
html = kwargs.pop("html", None)
text = kwargs.pop("text", None)
subject = kwargs.pop("subject", None)
super(TemplateMessage, self).__init__(**kwargs)
self._html_template = self._text_template = None
if html is not None:
_, _, inf, _ = self.loader(html)
self._html_template = MarkupTemplate(inf)
if text is not None:
_, _, inf, _ = self.loader(text)
self._text_template = NewTextTemplate(inf)
else:
self._text_template = None
if subject is not None:
_, _, inf, _ = self.loader(subject)
self._subject_template = NewTextTemplate(inf)
else:
self._subject_template = None
示例3: decorate_message
def decorate_message(self, event, message, decorates=None):
if event.realm == 'ticket':
if 'status' in event.changes:
action = 'Status -> %s' % (event.target['status'])
template = NewTextTemplate(
self.ticket_email_subject.encode('utf8'))
# Create a fallback for invalid custom Genshi template in option.
default_template = NewTextTemplate(
Option.registry[
('announcer', 'ticket_email_subject')
].default.encode('utf8'))
try:
subject = template.generate(
ticket=event.target,
event=event,
action=event.category
).render('text', encoding=None)
except TemplateError:
# Use fallback template.
subject = default_template.generate(
ticket=event.target,
event=event,
action=event.category
).render('text', encoding=None)
prefix = self.config.get('announcer', 'email_subject_prefix')
if prefix == '__default__':
prefix = '[%s] ' % self.env.project_name
if prefix:
subject = "%s%s" % (prefix, subject)
if event.category != 'created':
subject = 'Re: %s' % subject
set_header(message, 'Subject', subject)
return next_decorator(event, message, decorates)
示例4: _generate_from_template
def _generate_from_template(self, executable=False, **kwargs):
destination = kwargs['destination']
source = kwargs['source']
name = kwargs['name']
output_file = os.path.join(destination, name)
with open(source, 'r') as template:
template = NewTextTemplate(template)
context = Context(name=name, buildout=self.buildout, options=kwargs)
try:
output = template.generate(context).render()
except (TemplateSyntaxError, UndefinedError) as e:
raise zc.buildout.UserError(
'Error in template {0:s}:\n{1:s}'.format(name, e.msg))
if executable:
output = '#!{0:s}\n{1:s}'.format(sys.executable, output)
if executable and sys.platform == 'win32':
from pkg_resources import resource_string
exe = output_file + '.exe'
open(exe, 'wb').write(resource_string('setuptools', 'cli.exe'))
output_file = output_file + '-script.py'
with open(output_file, 'wb') as outfile:
outfile.write(output.encode('utf8'))
if executable:
self.logger.info('Generated script %r.', name)
try:
os.chmod(output_file, 493) # 0755 / 0o755
except (AttributeError, os.error):
pass
else:
self.logger.info('Generated file %r.', name)
示例5: create_genshi_raw_report
def create_genshi_raw_report(self, cr, uid, ids, data, report_xml, context=None, output='raw', tmpl=False):
def preprocess(data, aeroo_print):
aeroo_print.epl_images.reverse()
while aeroo_print.epl_images:
img = aeroo_print.epl_images.pop()
data = data.replace('<binary_data>', img, 1)
return data.replace('\n', '\r\n')
print_id = context.get('print_id', False)
aeroo_print = self.active_prints[print_id] # Aeroo print object
if not aeroo_print.start_time:
aeroo_print.start_time = time.time()
if not context:
context={}
context = context.copy()
objects = self.getObjects_mod(cr, uid, ids, report_xml.report_type, context)
oo_parser = self.parser(cr, uid, self.name2, context=context)
oo_parser.localcontext.update(context)
oo_parser.set_context(objects, data, ids, report_xml.report_type)
self.set_xml_data_fields(oo_parser.objects, oo_parser) # Get/Set XML
oo_parser.localcontext['data'] = data
oo_parser.localcontext['user_lang'] = context.get('lang', False)
if len(objects)>0:
oo_parser.localcontext['o'] = objects[0]
xfunc = ExtraFunctions(cr, uid, report_xml.id, oo_parser.localcontext)
oo_parser.localcontext.update(xfunc.functions)
model = context.get('active_model', data.get('model')) or data.get('model')
rec_id = context.get('active_id', data.get('id')) or data.get('id')
file_data = tmpl or context.get('aeroo_tmpl') or \
self.get_other_template(cr, uid, model, rec_id, oo_parser) or report_xml.report_sxw_content # Get other Template
if not file_data or file_data=='False':
raise osv.except_osv(_('Error!'), _('No template found!'))
################################################
if not file_data:
self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), logging.INFO) # debug mode
return False, output
print_id = context.get('print_id', False)
aeroo_print = self.active_prints[print_id]
oo_parser.localcontext['include_subreport'] = self._subreport(cr, uid, aeroo_print, output='raw', aeroo_ooo=False, context=context)
oo_parser.localcontext['epl2_gw'] = self._epl2_gw(aeroo_print)
deferred = context.get('deferred_process')
oo_parser.localcontext['progress_update'] = deferred and deferred.progress_update or (lambda:True)
aeroo_print.epl_images = []
basic = NewTextTemplate(source=base64.decodestring(file_data))
#try:
if genshi_version<='0.6':
data = preprocess(basic.generate(**oo_parser.localcontext).render().decode('utf8').encode(report_xml.charset), aeroo_print)
else:
data = preprocess(basic.generate(**oo_parser.localcontext).render().encode(report_xml.charset), aeroo_print)
#except Exception, e:
# self.logger(str(e), logging.ERROR)
# return False, output
if report_xml.content_fname:
output = report_xml.content_fname
self.logger("End process %s (%s), elapsed time: %s" % (self.name, self.table, time.time() - aeroo_print.start_time), logging.INFO) # debug mode
return data, output
示例6: render_genshi_tmpl
def render_genshi_tmpl(tmplstr, context, tmplpath=None):
'''
Render a Genshi template. A method should be passed in as part of the
context. If no method is passed in, xml is assumed. Valid methods are:
.. code-block:
- xml
- xhtml
- html
- text
- newtext
- oldtext
Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
is desired, it must be called explicitly
'''
method = context.get('method', 'xml')
if method == 'text' or method == 'newtext':
from genshi.template import NewTextTemplate
tmpl = NewTextTemplate(tmplstr)
elif method == 'oldtext':
from genshi.template import OldTextTemplate
tmpl = OldTextTemplate(tmplstr)
else:
from genshi.template import MarkupTemplate
tmpl = MarkupTemplate(tmplstr)
return tmpl.generate(**context).render(method)
示例7: convert
def convert(inputFile, templateFile, outputFile):
def preprocess(x):
return x
v = {
'delimiter' : ",",
'header' : None,
'footer' : '',
'preamble' : '',
'body' : '',
'skip_rows' : 0,
'process_rows' : 0,
'preprocess':preprocess
}
execfile(templateFile,{},v)
template = NewTextTemplate(v['body'])
#print v['preamble']
output = open(outputFile,'wb')
output.write(v['preamble'])
i = 0
for row in csv.DictReader(open(inputFile),fieldnames = v['header'], delimiter=v['delimiter']):
if v['skip_rows'] > 0:
print 'skipping', row
v['skip_rows'] -= 1
continue
i += 1
if v['process_rows'] > 0 and i > v['process_rows']:
break
row['linenum'] = str(i)
row = v['preprocess'](row)
if row == None: continue
o = template.generate(**row)
output.write(o.render())
output.write(v['footer'])
示例8: generate
def generate(self):
inf = open(self.source)
tmpl = NewTextTemplate(inf.read())
inf.close()
self.maybeMakeParentDir(self.target)
self.config.log.action('WRITE', self.target)
outf = open(self.target, 'w')
print >>outf, tmpl.generate(self.config.makeContext(self))
outf.close()
示例9: format_subject
def format_subject(self, transport, realm, style, event):
action = None
if transport == "email":
if realm == "ticket":
if event.changes:
if "status" in event.changes:
action = "Status -> %s" % (event.target["status"])
template = NewTextTemplate(self.ticket_email_subject)
return to_unicode(template.generate(ticket=event.target, event=event, action=action).render())
示例10: decorate_message
def decorate_message(self, event, message, decorates=None):
if event.realm == "blog":
template = NewTextTemplate(self.blog_email_subject.encode('utf8'))
subject = template.generate(
blog=event.blog_post,
action=event.category
).render('text', encoding=None)
set_header(message, 'Subject', subject)
return next_decorator(event, message, decorates)
示例11: render
def render(self):
log.debug("rendering genshi output")
from genshi.template import NewTextTemplate
if self.tmpl_content:
tmpl = NewTextTemplate(self.tmpl_content)
res = tmpl.generate(**self.data).render()
return res
else:
log.debug('template content is empty.')
return ''
示例12: _execute
def _execute(self):
from genshi.template import Context, NewTextTemplate
from genshi.template.eval import UndefinedError
template = NewTextTemplate(self.source)
context = Context(parts=self.buildout, options=self.options)
try:
self.result = template.generate(context).render()
except UndefinedError, e:
raise zc.buildout.UserError("Error in template %s:\n%s" % (self.input, e.msg))
示例13: render_string
def render_string(config, in_s):
'''Render a Genshi template as a string
:param config: data dictionary
:param in_s: genshi template
'''
tmpl = NewTextTemplate(in_s)
# older versions of python don't allow unicode keyword arguments
# so we have to encode the keys (for best compatibility in the client side tools)
config = _encode_unicode_keys(config)
return tmpl.generate(**config).render('text').decode('utf8')
示例14: render_fragmentTemplate
def render_fragmentTemplate(self,ctx,data):
sess = util.getStoreSession(ctx)
items = yield sess.getItems(fragmenttype.FragmentType)
for item in items:
if item.name == self.original.protectedObject.type:
fragmentType = item
break
template = fragmentType.template
from genshi.template import NewTextTemplate as TextTemplate
tmpl = TextTemplate(fragmentType.template)
output = tmpl.generate(**self.original.protectedObject.data)
returnValue(T.xml(output.render('text')))
示例15: process_script
def process_script(input_path, output_path):
'''
Given an input path, pass the script through genshi with the current gdb
context, writing it to the given output path.
'''
input_script = open(input_path, 'rt')
tmpl = NewTextTemplate(input_script)
stream = tmpl.generate(gdb=gdb)
output_script = open(output_path, 'wt')
output_script.write(stream.render())
output_script.close()
input_script.close()