Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
## 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
''''''
import sys, glob, mechanize, time, subprocess, os, shutil, re
from tempfile import NamedTemporaryFile
from genshi.template import TemplateLoader, MarkupTemplate
# Load libprs500 from source copy
sys.path.insert(1, os.path.dirname(os.path.dirname(os.getcwdu())))
from libprs500.ebooks.BeautifulSoup import BeautifulSoup
from libprs500.linux import entry_points
from libprs500 import __appname__, __author__, __version__
class Template(MarkupTemplate):
def generate(self, *args, **kwargs):
kwdargs = dict(app=__appname__, author=__author__.partition('<')[0].strip(),
version=__version__, footer=True)
kwdargs.update(kwargs)
return MarkupTemplate.generate(self, *args, **kwdargs)
loader = TemplateLoader(os.path.abspath('templates'), auto_reload=True,
variable_lookup='strict', default_class=Template)
def browser():
opener = mechanize.Browser()
opener.set_handle_refresh(True)
opener.set_handle_robots(False)
opener.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; i686 Linux; en_US; rv:1.8.0.4) Gecko/20060508 Firefox/1.5.0.4')]
return opener
% endfor
\
""")
def test_mako():
mako_template.render(**context)
try:
from genshi.template import MarkupTemplate as GenshiTemplate
except ImportError:
test_genshi = None
else:
genshi_template = GenshiTemplate("""\
<title>${page_title}</title>
<div class="header">
<h1>${page_title}</h1>
</div>
<ul class="navigation">
<li><a href="${href}">${caption}</a></li>
</ul>
<div class="table">
<table></table></div>
tmpl = mako.template.Template(**args)
return lambda kwargs: Markup(tmpl.render_unicode(**kwargs))
elif engine_name in ('genshi', 'genshi_abs'):
import genshi.template
args = dict(
source=src,
)
if directory:
args['loader'] = genshi.template.TemplateLoader([
genshi.template.loader.directory(directory),
])
tmpl = genshi.template.MarkupTemplate(**args)
return lambda kwargs: Markup(
''.join(tmpl.generate(**kwargs).serialize('xhtml'))
)
elif engine_name == 'jinja':
import jinja2
from .jinja_util import htmlbools
env = jinja2.environment.Environment(autoescape=True)
env.filters['htmlbools'] = htmlbools
tmpl = env.from_string(src, template_class=jinja2.Template)
tmpl.filename = filename
return lambda kwargs: Markup(tmpl.render(**kwargs))
elif engine_name == 'kajiki':
import kajiki
tmpl = kajiki.XMLTemplate(six.u(src), filename=filename,
t0 = pyperf.perf_counter()
for _ in range_it:
stream = tmpl.generate(table=table)
stream.render()
return pyperf.perf_counter() - t0
def add_cmdline_args(cmd, args):
if args.benchmark:
cmd.append(args.benchmark)
BENCHMARKS = {
'xml': (MarkupTemplate, BIGTABLE_XML),
'text': (NewTextTemplate, BIGTABLE_TEXT),
}
if __name__ == "__main__":
runner = pyperf.Runner(add_cmdline_args=add_cmdline_args)
runner.metadata['description'] = "Render a template using Genshi module"
runner.argparser.add_argument("benchmark", nargs='?',
choices=sorted(BENCHMARKS))
args = runner.parse_args()
if args.benchmark:
benchmarks = (args.benchmark,)
else:
benchmarks = sorted(BENCHMARKS)
% endfor
\
""")
def test_mako():
mako_template.render(**context)
try:
from genshi.template import MarkupTemplate as GenshiTemplate
except ImportError:
test_genshi = None
else:
genshi_template = GenshiTemplate("""\
<title>${page_title}</title>
<div class="header">
<h1>${page_title}</h1>
</div>
<ul class="navigation">
<li><a href="${href}">${caption}</a></li>
</ul>
<div class="table">
<table></table></div>
format = options.format
if format not in ('html', 'tex'):
raise ValueError("Unknown format: %s" % format)
if (format == 'tex') or (not options.template):
template = False
elif not isfile(options.template):
raise IOError("%r is not a valid template!" % options.template)
else:
template_path = abspath(options.template)
template_root = dirname(template_path)
template_loader = TemplateLoader([template_root])
template_file = open(template_path, 'rb')
template = MarkupTemplate(
template_file.read(), loader=template_loader, encoding='utf-8'
)
template_file.close()
data_file = options.data_file
if data_file:
if isfile(data_file):
data_file_obj = open(data_file, 'rb')
data_dict = load_pickle(data_file_obj)
data_file_obj.close()
else:
data_dict = {}
input_encoding = options.input_encoding
output_encoding = options.output_encoding
def generate(self, *args, **kwargs):
kwdargs = dict(app=__appname__, author=__author__.partition('<')[0].strip(),
version=__version__, footer=True)
kwdargs.update(kwargs)
return MarkupTemplate.generate(self, *args, **kwdargs)
def Index(self):
XMLFileBacked.Index(self)
if (self.name.endswith('.genshi') or
('py' in self.xdata.nsmap and
self.xdata.nsmap['py'] == 'http://genshi.edgewall.org/')):
try:
loader = genshi.template.TemplateLoader()
self.template = \
loader.load(self.name,
cls=genshi.template.MarkupTemplate,
encoding=Bcfg2.Options.setup.encoding)
except LookupError:
err = sys.exc_info()[1]
self.logger.error('Genshi lookup error in %s: %s' % (self.name,
err))
except genshi.template.TemplateError:
err = sys.exc_info()[1]
self.logger.error('Genshi template error in %s: %s' %
(self.name, err))
except genshi.input.ParseError:
err = sys.exc_info()[1]
self.logger.error('Genshi parse error in %s: %s' % (self.name,
err))
if HAS_CRYPTO and self.encryption:
for el in self.xdata.xpath("//*[@encrypted]"):
def get_genshi_template(name, klass=MarkupTemplate):
if name in GENSHI_TEMPLATE_CACHE:
return GENSHI_TEMPLATE_CACHE[name]
filepath = join_path(TEMPLATE_DIRECTORY, name+'.genshi')
template_data = open(filepath, 'U')
return GENSHI_TEMPLATE_CACHE.setdefault(
name, klass(template_data, filepath, name)
)