def generate(self, zone, json_data=None):
# compute local script location to find template_dir
me = os.path.realpath(__file__)
template_dir = os.path.dirname(me) + '/.'
self.d['domain'] = zone
# override with json
if json_data:
self.d.update(json.loads(json_data))
env = Environment(loader=FileSystemLoader(template_dir))
# add to_json filer in jinja2
# so json can be dumped with in jinja2: {{ var | to_json }}
env.filters['to_json'] = json.dumps
template = env.get_template(self.zonetemplate)
json_str = template.render(self.d)
return json_str
python类FileSystemLoader()的实例源码
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def __init__(self, templates_dir, openstack_release):
if not os.path.isdir(templates_dir):
log('Could not locate templates dir %s' % templates_dir,
level=ERROR)
raise OSConfigException
self.templates_dir = templates_dir
self.openstack_release = openstack_release
self.templates = {}
self._tmpl_env = None
if None in [Environment, ChoiceLoader, FileSystemLoader]:
# if this code is running, the object is created pre-install hook.
# jinja2 shouldn't get touched until the module is reloaded on next
# hook execution, with proper jinja2 bits successfully imported.
if six.PY2:
apt_install('python-jinja2')
else:
apt_install('python3-jinja2')
def init_jinja2(app, **kwargs):
logging.info('init jinja2...')
options = dict(
autoescape = kwargs.get('autoescape', True),
block_start_string = kwargs.get('block_start_string', '{%'),
block_end_string = kwargs.get('blcok_end_string', '%}'),
variable_start_string = kwargs.get('variable_start_string', '{{'),
variable_end_string = kwargs.get('variable_end_string', '}}'),
auto_reload = kwargs.get('auto_reload', True)
)
path = kwargs.get('path', None)
if path is None:
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
logging.info('set jinja2 template path: {}'.format(path))
env = Environment(loader = FileSystemLoader(path), **options)
filters = kwargs.get('filters', None)
if filters is not None:
for name, f in filters.items():
env.filters[name] = f
app['__templating__'] = env
def prepare_packer_template(config, template_name):
"""
Prepares a packer template JSON file according to configuration and writes
it into a temporary location where packer later expects it.
Uses jinja2 template syntax to generate the resulting JSON file.
Templates are in templates/ and snippets in templates/snippets/.
"""
try:
template_fd = resource_stream(__name__,
'templates/{}.json'.format(template_name))
except FileNotFoundError:
print("Template doesn't exist: {}".format(template_name))
sys.exit(2)
filepath = resource_filename(__name__, 'templates/')
env = Environment(loader=FileSystemLoader(filepath), autoescape=False,
trim_blocks=True, lstrip_blocks=True)
template = env.get_template("{}.json".format(template_name))
# write to temporary file
f = create_cachefd('{}.json'.format(template_name))
f.write(template.render(config)) # pylint: disable=no-member
f.close()
return f.name
def __jinja_render_to_file(cls, template_path, template_file, module_name,
temp_dir, module_path, **context):
"""
Create the module from a jinja template.
:param template_file: name of the template file
:param module_name: the destination file name
:param temp_dir: a temporary working dir for jinja
:param context: dict of substitution variables
:return: None
"""
j2_tmpl_path = template_path
j2_env = Environment(loader=FileSystemLoader(j2_tmpl_path), keep_trailing_newline=True)
j2_tmpl = j2_env.get_template(template_file)
rendered = j2_tmpl.render(dict(temp_dir=temp_dir, **context))
with open(os.path.normpath(os.path.join(module_path, module_name)), 'wb') as f:
f.write(rendered.encode('utf8'))
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def create_initial_app(self):
#Create app directory
os.makedirs('app')
template_path = Path(__file__).ancestor(1).child('templates')
#Create Jinja2 Environment
env = Environment(autoescape=False,
loader=FileSystemLoader(template_path))
#Get flask and zappa_settings templates
flask_app_template = env.get_template('flask.py.jinja2')
zappa_settings_template = env.get_template(
'zappa_settings.json.jinja2')
#Create Flask app and zappa_settings.json files in the app directory
with open('app/{app_name}.py'.format(app_name=self.app_name), 'w+') as f:
f.write(flask_app_template.render(app_name=self.app_name, stage_name=self.stage_name))
with open('app/zappa_settings.json'.format(app_name=self.app_name), 'w+') as f:
f.write(zappa_settings_template.render(app_name=self.app_name,
stage_name=self.stage_name,
function_bucket=self.function_bucket,
aws_region_name=self.aws_region_name))
#Copy the HTML template to the app/templates directory
shutil.copytree(template_path.child('templates'), 'app/templates')
def get_app():
redis = await aioredis.create_redis(('localhost', 6379,), db=1)
app = web.Application()
app['redis'] = redis
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates/'),
context_processors=(static_processor,))
app.router.add_route('GET', '/', handlers.index)
app.router.add_route('GET', '/login', handlers.login_task)
app.router.add_route('POST', '/login', handlers.login)
app.router.add_static('/static', 'static')
async def close_redis(app):
app['redis'].close()
app.on_shutdown.append(close_redis)
return app
def jinja2_environment(template_dir, typ):
env = Environment(loader=FileSystemLoader(template_dir),
variable_start_string="@{",
variable_end_string="}@",
trim_blocks=True)
env.globals['xline'] = rst_xline
if typ == 'rst':
env.filters['convert_symbols_to_format'] = rst_ify
env.filters['html_ify'] = html_ify
env.filters['fmt'] = rst_fmt
env.filters['xline'] = rst_xline
template = env.get_template('plugin.rst.j2')
outputname = "%s_module.rst"
else:
raise Exception("unknown module format type: %s" % typ)
return env, template, outputname
def __init__(self):
super(Environment, self).__init__(
loader=jinja2.FileSystemLoader(path.join(path.dirname(__file__), 'ui/templates')),
extensions=[jinja2.ext.with_],
auto_reload=options.debug,
autoescape=True,
trim_blocks=True,
undefined=Undefined)
globals()[self.__class__.__name__] = lambda: self # singleton
self.globals['vj4'] = vj4
self.globals['static_url'] = lambda s: options.cdn_prefix + staticmanifest.get(s)
self.globals['paginate'] = misc.paginate
self.filters['nl2br'] = misc.nl2br
self.filters['markdown'] = misc.markdown
self.filters['json'] = json.encode
self.filters['gravatar_url'] = misc.gravatar_url
self.filters['format_size'] = misc.format_size
self.filters['format_seconds'] = misc.format_seconds
self.filters['base64_encode'] = misc.base64_encode
def jinja_render(path, context, functions=(), ignore_undefined=False):
kwargs = {}
if ignore_undefined:
kwargs['undefined'] = SilentUndefined
else:
kwargs['undefined'] = jinja2.StrictUndefined
env = jinja2.Environment(loader=jinja2.FileSystemLoader(
os.path.dirname(path)), **kwargs)
env.filters['host'] = get_host
# FIXME: gethostbyname should be only used during config files render
env.filters['gethostbyname'] = lambda x: x
for func in functions:
env.globals[func.__name__] = func
env.globals['raise_exception'] = j2raise
content = env.get_template(os.path.basename(path)).render(context)
return content
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def __init__(self, templates_dir, openstack_release):
if not os.path.isdir(templates_dir):
log('Could not locate templates dir %s' % templates_dir,
level=ERROR)
raise OSConfigException
self.templates_dir = templates_dir
self.openstack_release = openstack_release
self.templates = {}
self._tmpl_env = None
if None in [Environment, ChoiceLoader, FileSystemLoader]:
# if this code is running, the object is created pre-install hook.
# jinja2 shouldn't get touched until the module is reloaded on next
# hook execution, with proper jinja2 bits successfully imported.
if six.PY2:
apt_install('python-jinja2')
else:
apt_install('python3-jinja2')
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def __init__(self, templates_dir, openstack_release):
if not os.path.isdir(templates_dir):
log('Could not locate templates dir %s' % templates_dir,
level=ERROR)
raise OSConfigException
self.templates_dir = templates_dir
self.openstack_release = openstack_release
self.templates = {}
self._tmpl_env = None
if None in [Environment, ChoiceLoader, FileSystemLoader]:
# if this code is running, the object is created pre-install hook.
# jinja2 shouldn't get touched until the module is reloaded on next
# hook execution, with proper jinja2 bits successfully imported.
if six.PY2:
apt_install('python-jinja2')
else:
apt_install('python3-jinja2')
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def render_and_write(template_dir, path, context):
"""Renders the specified template into the file.
:param template_dir: the directory to load the template from
:param path: the path to write the templated contents to
:param context: the parameters to pass to the rendering engine
"""
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
rendered_content = template.render(context)
if not rendered_content:
log("Render returned None - skipping '%s'" % path,
level=WARNING)
return
write(path, rendered_content.encode('utf-8').strip())
log('Wrote template %s' % path, level=DEBUG)
def __init__(self, templates_dir, openstack_release):
if not os.path.isdir(templates_dir):
log('Could not locate templates dir %s' % templates_dir,
level=ERROR)
raise OSConfigException
self.templates_dir = templates_dir
self.openstack_release = openstack_release
self.templates = {}
self._tmpl_env = None
if None in [Environment, ChoiceLoader, FileSystemLoader]:
# if this code is running, the object is created pre-install hook.
# jinja2 shouldn't get touched until the module is reloaded on next
# hook execution, with proper jinja2 bits successfully imported.
if six.PY2:
apt_install('python-jinja2')
else:
apt_install('python3-jinja2')