本文整理汇总了Python中pyjade.utils.process函数的典型用法代码示例。如果您正苦于以下问题:Python process函数的具体用法?Python process怎么用?Python process使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了process函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_template
def load_template(self, template_name, template_dirs=None):
key = template_name
if template_dirs:
# If template directories were specified, use a hash to differentiate
key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])
if settings.DEBUG or key not in self.template_cache:
if os.path.splitext(template_name)[1] in ('.jade',):
source, display_name = self.load_template_source(template_name, template_dirs)
source=process(source,filename=template_name,compiler=Compiler)
origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
template = get_template_from_string(source, origin, template_name)
else:
template, origin = self.find_template(template_name, template_dirs)
if not hasattr(template, 'render'):
try:
template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
except TemplateDoesNotExist:
# If compiling the template we found raises TemplateDoesNotExist,
# back off to returning he source and display name for the template
# we were asked to load. This allows for correct identification (later)
# of the actual template that does not exist.
return template, origin
self.template_cache[key] = template
return self.template_cache[key], None
示例2: templatize
def templatize(src, origin=None):
src = to_text(src, settings.FILE_CHARSET)
if origin.endswith(".jade"):
html = process(src,compiler=Compiler)
else:
html = src
return func(html, origin)
示例3: preprocess
def preprocess(self, source, name, filename=None):
if (not name or
(name and not os.path.splitext(name)[1] in self.file_extensions)):
msg = "return {}".format(name)
logging.info(msg)
return source
return process(source,filename=name,compiler=Compiler,**self.options)
示例4: django_process
def django_process(str):
compiled = process(str,filename=None,compiler = DjangoCompiler)
print(compiled)
t = django.template.Template(compiled)
ctx = django.template.Context()
return t.render(ctx)
示例5: django_process
def django_process(src, filename):
compiled = process(src, filename=filename,compiler = DjangoCompiler)
print compiled
t = django.template.Template(compiled)
ctx = django.template.Context()
return t.render(ctx)
示例6: upgrade
def upgrade():
op.add_column('application_template', sa.Column('jinja2', sa.Text))
op.add_column('application_template', sa.Column('key', sa.String(255)))
meta = sa.MetaData()
table = sa.schema.Table(
'application_template', meta,
sa.Column('id', sa.BigInteger, primary_key=True),
sa.Column('key', sa.String(255)),
sa.Column('jinja2', sa.Text)
)
# converting original jade template_source into jinja2 preprocessed source
conn = op.get_bind()
rows = conn.execute('select id, template_key, template_source from application_template')
for row in rows:
rid = row[0]
name = row[1]
source = row[2]
results = process(source,filename=name,compiler=Compiler)
where = 'id=%d' % rid
update_expression = sa.sql.expression.update(
table, whereclause=where,
values={
'jinja2': results,
'key': name
}
)
conn.execute(update_expression)
示例7: convert_file
def convert_file():
support_compilers_list = ['django', 'jinja', 'underscore', 'mako', 'tornado', 'html']
available_compilers = {}
for i in support_compilers_list:
try:
compiler_class = __import__('pyjade.ext.%s' % i, fromlist=['pyjade']).Compiler
except ImportError as e:
logging.warning(e)
else:
available_compilers[i] = compiler_class
usage = "usage: %prog [options] [file [output]]"
parser = OptionParser(usage)
parser.add_option("-o", "--output", dest="output",
help="Write output to FILE", metavar="FILE")
# use a default compiler here to sidestep making a particular
# compiler absolutely necessary (ex. django)
default_compiler = sorted(available_compilers.keys())[0]
parser.add_option("-c", "--compiler", dest="compiler",
choices=list(available_compilers.keys()),
default=default_compiler,
type="choice",
help=("COMPILER must be one of %s, default is %s" %
(', '.join(list(available_compilers.keys())), default_compiler)))
parser.add_option("-e", "--ext", dest="extension",
help="Set import/extends default file extension",
metavar="FILE")
options, args = parser.parse_args()
file_output = options.output or (args[1] if len(args) > 1 else None)
compiler = options.compiler
if options.extension:
extension = '.%s' % options.extension
elif options.output:
extension = os.path.splitext(options.output)[1]
else:
extension = None
if compiler in available_compilers:
import six
if len(args) >= 1:
template = codecs.open(args[0], 'r', encoding='utf-8').read()
elif six.PY3:
template = sys.stdin.read()
else:
template = codecs.getreader('utf-8')(sys.stdin).read()
output = process(template, compiler=available_compilers[compiler],
staticAttrs=True, extension=extension)
if file_output:
outfile = codecs.open(file_output, 'w', encoding='utf-8')
outfile.write(output)
elif six.PY3:
sys.stdout.write(output)
else:
codecs.getwriter('utf-8')(sys.stdout).write(output)
else:
raise Exception('You must have %s installed!' % compiler)
示例8: __init__
def __init__(self, template_string, name="<string>", *args, **kwargs):
is_jade = name.endswith(".jade")
if is_jade:
template_string = process(template_string, filename=name, compiler=Compiler)
super(Template, self).__init__(template_string, name, *args, **kwargs)
if is_jade:
self.namespace.update({ATTRS_FUNC: attrs, ESCAPE_FUNC: escape, ITER_FUNC: iteration})
示例9: _convert
def _convert(src, dst):
template = codecs.open(src, "r", encoding="utf-8").read()
output = process(template, compiler=UnderscoreCompiler)
outfile = codecs.open(dst, "w", encoding="utf-8")
outfile.write(output)
outfile.close()
print 'compiled "%s" into "%s"' % (src, dst)
示例10: preprocess
def preprocess(self, source, name, filename=None):
if name and not os.path.splitext(name)[1] in self.environment.jade_file_extensions:
return source
return process(source,filename=name,compiler=Compiler)
# parser = Parser(source,filename=name)
# block = parser.parse()
# compiler = Compiler(block)
# return compiler.compile()
# procesed= process(source,name)
# print procesed
# return procesed
示例11: convert_file
def convert_file():
import codecs
aviable_compilers = {}
try:
from pyjade.ext.django import Compiler as DjancoCompiler
aviable_compilers['django'] = DjancoCompiler
except:
pass
try:
from pyjade.ext.jinja import Compiler as JinjaCompiler
aviable_compilers['jinja'] = JinjaCompiler
except:
pass
try:
from pyjade.ext.underscore import Compiler as UnderscoreCompiler
aviable_compilers['underscore'] = UnderscoreCompiler
except:
pass
try:
from pyjade.ext.mako import Compiler as MakoCompiler
aviable_compilers['mako'] = MakoCompiler
except:
pass
from optparse import OptionParser
usage = "usage: %prog [options] file [output]"
parser = OptionParser(usage)
parser.add_option("-o", "--output", dest="output",
help="write output to FILE", metavar="FILE")
parser.add_option("-c", "--compiler", dest="compiler",
choices=['django', 'jinja', 'mako', 'underscore',],
default='django',
type="choice",
help="COMPILER must be django (default), jinja, underscore or mako ")
# parser.add_option("-q", "--quiet",
# action="store_false", dest="verbose", default=True,
# help="don't print status messages to stdout")
(options, args) = parser.parse_args()
if len(args)<1:
print "Specify the input file as the first argument."
exit()
file_output = options.output or (args[1] if len(args)>1 else None)
compiler = options.compiler
if compiler in aviable_compilers:
template = codecs.open(args[0], 'r', encoding='utf-8').read()
output = process(template,compiler=aviable_compilers[compiler])
if file_output:
outfile = codecs.open(file_output, 'w', encoding='utf-8')
outfile.write(output)
else:
print output
else:
raise Exception('You must have %s installed!'%compiler)
示例12: load_template
def load_template(self, template_name, template_dirs=None):
if os.path.splitext(str(template_name))[1] in ('.jade',):
try:
source, display_name = self.load_template_source(template_name, template_dirs)
source=process(source,filename=template_name,compiler=Compiler)
origin = make_origin(display_name, self.load_template_source, template_name, template_dirs)
template = get_template_from_string(source, origin, template_name)
except NotImplementedError:
template, origin = self.find_template(template_name, template_dirs)
else:
template, origin = self.find_template(template_name, template_dirs)
if not hasattr(template, 'render'):
try:
template = get_template_from_string(process(source,filename=template_name,compiler=Compiler), origin, template_name)
except TemplateDoesNotExist:
# If compiling the template we found raises TemplateDoesNotExist,
# back off to returning he source and display name for the template
# we were asked to load. This allows for correct identification (later)
# of the actual template that does not exist.
return template, origin
return template, None
示例13: run_case
def run_case(case,process):
global processors
process = processors[process]
jade_file = open('cases/%s.jade'%case)
jade_src = jade_file.read().decode('utf-8')
jade_file.close()
html_file = open('cases/%s.html'%case)
html_src = html_file.read().strip('\n').decode('utf-8')
html_file.close()
try:
processed_jade = process(jade_src).strip('\n')
print 'PROCESSED\n',processed_jade,len(processed_jade)
print 'EXPECTED\n',html_src,len(html_src)
assert processed_jade==html_src
except CurrentlyNotSupported:
pass
示例14: render_jade_with_json
def render_jade_with_json(self, jade_template_path, json_file_path,
template_path_base, base_file):
logger.debug('Working with jade template %s', jade_template_path)
tmpl = loader.get_template(jade_template_path)
if settings.DEBUG:
logger.debug('Template is: %s',
process(open(os.path.join(self.template_path,
jade_template_path)).read()))
# We need to simulate request middleware but without short-circuiting
# the response
request_factory = RequestFactory()
req = request_factory.get('/%s/%s.html' % (template_path_base,
base_file),
data={})
handler = WSGIHandler()
handler.load_middleware()
for middleware_method in handler._request_middleware:
middleware_method(req)
# Render the template with a RequestContext
ctx = RequestContext(req, json.load(open(json_file_path)))
return tmpl.render(ctx)
示例15: compile
def compile(self, base_file_name, path, template_path):
jade_template_path = os.path.join(template_path,
'%s.jade' % (base_file_name,))
logger.debug('Working with jade template %s', jade_template_path)
# Change the pwd to the template's location
current_pwd = os.getcwd()
os.chdir(path)
# Hackery to allow for pre-processing the jade source
jade_loader = Loader(
('django.template.loaders.filesystem.Loader',))
tmpl_src, display_name = jade_loader.load_template_source(
jade_template_path, [self.template_path,])
if self.INCLUDE_RE.search(tmpl_src):
tmpl_src = self.preprocess_includes(tmpl_src)
# WHITESPACE! HUH! WHAAAAT IS IT GOOD FOR? ABSOLUTELY NOTHING!
tmpl_src = u'\n'.join([line for line in tmpl_src.split('\n')
if line.strip()])
origin = loader.make_origin(display_name,
jade_loader.load_template_source,
jade_template_path, None)
if settings.DEBUG:
logger.debug(
u'Template is: \n%s',
u'\n'.join(['%4d: %s' % (i, s)
for i, s in enumerate(tmpl_src.split('\n'))]))
compiled_jade = process(tmpl_src, filename=jade_template_path,
compiler=Compiler)
try:
tmpl = loader.get_template_from_string(compiled_jade, origin,
jade_template_path)
except Exception, e:
logger.exception('Failed to compile Jade-derived HTML template:')
logger.exception(
u'\n'.join(['%4d: %s' % (i, s)
for i, s in enumerate(compiled_jade.split(u'\n'))]))
raise