我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用jinja2.PackageLoader()。
def encode(self, api_input, action): """Transform input to dummy zpl.""" if not (action in DUMMY_ACTIONS): raise Exception( 'action %s not in %s' % (action, ', '.join(DUMMY_ACTIONS))) api = DummyApi() if not api.validate(api_input): raise InvalidApiInput( 'Input error : %s' % api.errors(api_input)) data = api.normalize(api_input) data['to_address']['dept'] = data['to_address']['zip'][0:2] env = Environment( loader=PackageLoader('roulier', '/carriers/dummy/templates'), extensions=['jinja2.ext.with_']) template = env.get_template("dummy_%s.zpl" % action) return template.render( auth=data['auth'], service=data['service'], parcel=data['parcel'], sender_address=data['from_address'], receiver_address=data['to_address'])
def get_domain_template(distro, libvirt_ver, **kwargs): """ Get a rendered Jinja2 domain template Args: distro(str): domain distro libvirt_ver(int): libvirt version kwargs(dict): args for template render Returns: str: rendered template """ env = Environment( loader=PackageLoader('lago', 'providers/libvirt/templates'), trim_blocks=True, lstrip_blocks=True, ) template_name = 'dom_template-{0}.xml.j2'.format(distro) try: template = env.get_template(template_name) except TemplateNotFound: LOGGER.debug('could not find template %s using default', template_name) template = env.get_template('dom_template-base.xml.j2') return template.render(libvirt_ver=libvirt_ver, **kwargs)
def get_template_engine(self): engine = self.get('template_engine') if engine is None: templates = self['templates'] dirname = os.path.join(os.getcwd(), 'templates') if os.path.isdir(dirname): # pragma: no cover if dirname not in templates: templates.insert(0, dirname) elif os.getcwd() not in templates: templates.insert(0, os.getcwd()) loader = jinja2.ChoiceLoader([ FileSystemLoader(p) for p in templates ] + [jinja2.PackageLoader('nuka')]) self['template_engine'] = jinja2.Environment( loader=loader, undefined=jinja2.StrictUndefined, keep_trailing_newline=True, autoescape=False, ) return self['template_engine']
def launchCmd(self, inputs, tmpStore, stdout_file): mesh = inputs['mesh'] absPath = os.path.abspath(os.path.join('/data', mesh.path)) env = Environment( loader=PackageLoader('pkg_codeaster.tools', 'templates') ) templatePara = env.get_template('paraview_warp_by_displacement_template.py') with open('disp_warp_output_script.py', 'w') as file: file.write(templatePara.render(input_mesh=absPath)) return {'script_file': 'disp_warp_output_script.py' }
def launchCmd(self, inputs, tmpStore, stdout_file): mesh = inputs['mesh'] absPath = os.path.abspath(os.path.join('/data', mesh.path)) env = Environment( loader=PackageLoader('pkg_codeaster.tools', 'templates') ) templatePara = env.get_template('paraview_clip_template.py') with open('clip_output_script.py', 'w') as file: file.write(templatePara.render(input_mesh=absPath)) return {'script_file': 'clip_output_script.py' }
def launchCmd(self, inputs, tmpStore, stdout_file): mesh = inputs['mesh'] absPath = os.path.abspath(os.path.join('/data', mesh.path)) env = Environment( loader=PackageLoader('pkg_codeaster.tools', 'templates') ) templatePara = env.get_template('paraview_stress_warp_template.py') with open('stress_warp_output_script.py', 'w') as file: file.write(templatePara.render(input_mesh=absPath)) return {'script_file': 'stress_warp_output_script.py' }
def launchCmd(self, inputs, tmpStore, stdout_file): mesh = inputs['mesh'] absPath = os.path.abspath(os.path.join('/data', mesh.path)) env = Environment( loader=PackageLoader('pkg_codeaster.tools', 'templates') ) templatePara = env.get_template('paraview_surfacegrid_template.py') with open('surfacegrid_output_script.py', 'w') as file: file.write(templatePara.render(input_mesh=absPath)) return {'script_file': 'surfacegrid_output_script.py' }
def get_mapping(cls): from pyplanet.core import Controller mapping = dict() # Static core components. mapping['core.views'] = PackageLoader('pyplanet.views', 'templates') # Add app prefixes. for app_label, app in Controller.instance.apps.apps.items(): template_path = os.path.join(app.path, 'templates') if os.path.exists(template_path): mapping[app_label] = FileSystemLoader(template_path) return mapping
def create_index(self): """ Creates an HTML index page to redirect to an MkDocs generated page. """ from jinja2 import Environment, PackageLoader, select_autoescape env = Environment( loader=PackageLoader('wikidoc', 'templates'), autoescape=select_autoescape(['html', 'xml']) ) template = env.get_template('redirect.html') html_code = template.render(target_url=self._index) file_name = os.path.join(self._out_dir, "index.html") if not os.path.exists(file_name): with open(file_name, "w") as index_file: index_file.write(html_code)
def setup_fallback_env(): env = jinja2.Environment(loader=jinja2.PackageLoader(__name__)) env.lstrip_blocks = True env.trim_blocks = True return env
def render_control(self): host_port = self.exposed host_name = self.instance_name env = Environment(loader=PackageLoader('cthulhu', 'templates')) template = env.get_template('instance-control.sh') # TODO(sholsapp): How can we make this generic but meaningful? We always will # need to know a little bit about the application here, so maybe we should # ask for a fixture.spec or something? return template.render( docker_container=self.container, host_name=host_name, host_port=host_port, local_etc=self.node_etc, local_root=self.node_root, local_var=self.node_var, name=self.instance_name, )
def render_control(self): env = Environment(loader=PackageLoader('cthulhu', 'templates')) template = env.get_template('fixture-control.sh') return template.render( instances=self.instances, )
def __init__(self): super(TextFormatter, self).__init__() env = Environment(loader=PackageLoader('gixy', 'formatters/templates'), trim_blocks=True, lstrip_blocks=True) self.template = env.get_template('text.j2')
def __init__(self): super(ConsoleFormatter, self).__init__() env = Environment(loader=PackageLoader('gixy', 'formatters/templates'), trim_blocks=True, lstrip_blocks=True) self.template = env.get_template('console.j2')
def get_app(loop, data_queue): app = web.Application() app['sockets'] = [] mainhandler = MainHandler() redishandler = RedisHanlder(data_queue) app.router.add_route("GET", '/', mainhandler.get) app.router.add_route("*", '/data', redishandler.get) app.router.add_static('/static/', path=str(PROJ_ROOT / 'static/css'), name='static') aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('src', 'static')) srv = await loop.create_server(app.make_handler(), "0.0.0.0", port=9999) return srv
def initialize(loop: asyncio.AbstractEventLoop, port: int, username: str, password: str, dbcon: DBConnection, active_monitor_manager: ActiveMonitorManager) -> None: """Initialize the webmgmt listener.""" stats.set('num_calls', 0, 'WEBMGMT') app = web.Application(loop=loop, logger=log.logger, middlewares=[ middleware.logging_middleware_factory, middleware.error_handler_middleware_factory, middleware.basic_auth_middleware_factory, ]) app['username'] = username app['password'] = password app['dbcon'] = dbcon app['active_monitor_manager'] = active_monitor_manager setup_routes(app) aiohttp_jinja2.setup( app, loader=jinja2.PackageLoader('irisett.webmgmt', 'templates'), filters={ 'timestamp': jinja_filters.timestamp }, ) listener = loop.create_server(app.make_handler(), '0.0.0.0', port) asyncio.ensure_future(listener) log.msg('Webmgmt listening on port %s' % port)
def create_jinja_loader(self): return PackageLoader(self.app_name)
def update(self, services, fqdn="flyby.example.com", resolvers=None, log_endpoint=None, log_format=None): logger.debug("Updating HAProxy configs...") resolvers = resolvers if resolvers else [] env = Environment(loader=PackageLoader('flyby', 'config')) template = env.get_template('haproxy.cfg.j2') tempate_params = dict( fqdn=fqdn, services=self._filter_services(services), resolvers=resolvers, log_endpoint=log_endpoint, log_format=log_format ) c = template.render(**tempate_params) if self.config != c: logger.debug("Changed configs identified.") self.config = c self._run() logger.debug("HAProxy configs successfully updated.") else: logger.debug("HAProxy configs up-to-date. Nothing to do.")
def __init__(self, protocol, config): self.env = Environment(loader=PackageLoader('piqueserver.web')) self.protocol = protocol root = Resource() root.putChild(b'json', JSONPage(self)) root.putChild(b'', StatusPage(self)) root.putChild(b'overview', MapOverview(self)) site = server.Site(root) logging = config.get('logging', False) site.noisy = logging if not logging: site.log = lambda _: None protocol.listenTCP(config.get('port', 32886), site)
def __init__(self, template_fn='standard.html'): self.output_dir = config.output_dir self.path = "./" # Initiate jinja template env = Environment( loader=PackageLoader('sequana', 'resources/templates/') ) self.template = env.get_template(template_fn) self._init_report()
def __init__(self, pkg_data): """Initialize.""" self.cwd = os.getcwd() self.name = pkg_data.name self.outdir = os.path.abspath(pkg_data.outdir) self.tmpdir = tempfile.mkdtemp(suffix=self.suffix) self.templates = Environment(loader=PackageLoader(self.template_name)) self.pkg_data = pkg_data
def __init__(self, controller_or_app): self.app = controller_or_app.app if hasattr(controller_or_app, 'app') else controller_or_app self.env = jinja2.Environment( loader=jinja2.ChoiceLoader( ( jinja2.PackageLoader('pycommunicate'), jinja2.FileSystemLoader(self.app.template_directory) ) ) ) def add_includes(): return self.render_includes() self.env.globals.update({ 'add_includes': add_includes })
def __init__(self, args): self.args = args with open(args.input, 'r') as f: self.json = json.load(f) self._validate_config() self._build_api() self.name = self.json["Name"] self.jinja_env = Environment(loader=PackageLoader('downtoearth', 'templates'))
def render_template(template_name, **kwargs): """ Simple utility function to render out a specified template, using **kwargs to fill in variables. Args: template_path (str): The directory where we can find the template. template_name (str): The actual name of the template we want to render. **kwargs (dict): Key Value pairs of any variables we want rendered out into the template. Raises: AncillaryFileNotFound: If we cannot find the template. AncillaryUndefinedError: If we run across an undefined variable. """ # Attempt to load a Tempalte file from within the 'Zapper' package # and raise an IOError if I'm unable to find it. try: env = Environment(loader=PackageLoader('zapper', 'templates')) template = env.get_template(template_name) except TemplateNotFound: raise IOError('Unable to find template {} in zapper!' .format(template_name)) # Attempt to render our template, and raise a Value Error if we # run into any undefined variables. try: template_data = template.render(**kwargs) except UndefinedError as e: raise ValueError('Undefined variable found in {}! Error: {}' .format(template_name, e)) return template_data
def _generate_data(output_file, context, template_file, default_template): if not template_file: env = Environment(loader=PackageLoader("proxmoxdeploy.cloudinit")) template = env.get_template(default_template) else: template = Template(template_file.read()) with open(output_file, "w") as output: output.write(template.render(context=context))
def calibrate(): print("Configuring Wordpress installer") log_location = os.path.dirname(__file__) + '/resources/wordpress_installer.log' try: os.remove(log_location) except Exception as e: pass env = Environment(loader=PackageLoader('wordpress_installer', '/resources/templates')) log_config_template = env.get_template('logging_config.ini.j2') log_config = log_config_template.render(LOG_LOCATION=log_location) log_config_location = os.path.dirname(__file__) + "/resources/logging_config.ini" with open(log_config_location, "w") as fh: fh.write(log_config) print("Writing Files Complete!")
def create_wordpress_conf(user_dir, db_conf): """ Used to generate a new wordpress configuration file from a jinja2 template. Pulls the configuration keys from the wordpress API and injects them into the template. Injects the database configuration returned from create_wordpress_database into database details of the template. Writes the newly templated configuration file into the wordpress directory. """ logger.debug("Generating wordpress configuration") env = Environment(loader=PackageLoader('wordpress_installer', '/resources/templates')) template = env.get_template('wp-config.php.j2') def get_wordpress_conf_keys(): logger.debug("Fetching wordpress configuration") response = requests.get("https://api.wordpress.org/secret-key/1.1/salt/") return response.text wordpress_config = template.render(USER_DIR=user_dir, DB_NAME=db_conf["db"], DB_USER=db_conf["user"], DB_PASSWORD=db_conf["password"], DB_HOST=db_conf["host"], KEYS=get_wordpress_conf_keys()) logger.debug("Wordpress configuration rendered from template, writing to file") with open(user_dir + "/public_html/wordpress/wp-config.php", "w") as fh: fh.write(wordpress_config)
def gen_dockerfiles(envs): tpl_env = Environment(loader=PackageLoader('ibench', 'docker')) for env in envs: with open(dockerfileName(env),'w') as df: df.write(tpl_env.get_template('Dockerfile.tpl').render(env)) #os_default = ['centos','ubuntu']
def set_package_loader(app): aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('tests.contrib.aiohttp.app', 'templates'))
def start(self): """Start aiohttp web server.""" self.app = web.Application() aiohttp_jinja2.setup( self.app, loader=jinja2.PackageLoader('aiohttp_server', 'templates'), # enable_async=False, auto_reload=False) aiohttp_session.setup(self.app, aiohttp_session.SimpleCookieStorage()) self.add_routes() self.handler = self.app.make_handler() self.f = self.loop.create_server(self.handler, host='0.0.0.0', port=self.port) # Event loop is already running, so we await create server instead # of run_until_complete self.srv = await self.f
def __init__(self, loop=None, port=None, db=None): """Init AiohttpTarantoolOne with loop, port and db.""" super().__init__(loop=loop, port=port) self.db = db self.statistics = { "packs_count": "empty", "stickers_count": "empty", "clicks": "empty", "votes": "empty", "users": "empty"} self.jinja = Environment( loader=PackageLoader('aiohttp_server', 'templates'), # enable_async=False, auto_reload=False)
def run(self): env = Environment(loader=PackageLoader('web')) t = env.get_template('summary.html') title = 'Summary for search "%s"' % self.term t.stream(title=title).dump(self.output().fn)
def __init__(self, package, path): self.env = Environment( loader=PackageLoader(package, path), autoescape=select_autoescape(['html']) ) self.env.filters['basename'] = lambda s: os.path.basename(s) self.env.filters['media'] = \ lambda url, ts, *a: shortcuts.reverse_media_url(ts, url, *a)
def export_html(self, include_recibo_sacado=True, static_url=None): ''' Gera e retorna o boleto em HTML ''' env = Environment(loader=PackageLoader('python_boleto', 'templates')) env.filters['index_or_blank'] = filters.index_or_blank env.filters['format_currency_or_blank'] = filters.format_currency_or_blank env.filters['format_date_or_blank'] = filters.format_date_or_blank env.filters['format_agencia_conta'] = filters.format_agencia_conta template = env.get_template(self._template) context_data = self.get_context_data() or {} # Monta a URL do logo do banco logo_url = self._logo if static_url: logo_url = urljoin(static_url, self._logo) context_data['logo_url'] = logo_url # gera o barse64 do logo, se possível try: logo_img_file = os.path.join(STATIC_DIR, self._logo) if os.path.exists(logo_img_file): img = open(logo_img_file, "rb") context_data['logo_base64'] = base64.b64encode(img.read()).decode('utf-8') except: logger.exception("Erro ao converter logo em Base64") return template.render(boleto=self, include_recibo_sacado=include_recibo_sacado, **context_data)
def rst(self, partial_path, full_path, doclet, use_short_name=False): """Return rendered RST about an entity with the given name and doclet.""" dotted_name = partial_path[-1] if use_short_name else _dotted_path(partial_path) # Render to RST using Jinja: env = Environment(loader=PackageLoader('sphinx_js', 'templates')) template = env.get_template(self._template) return template.render(**self._template_vars(dotted_name, full_path, doclet))
def encode(self, api_input, action): """Transform input to laposte compatible xml.""" if not (action in LAPOSTE_ACTIONS): raise InvalidApiInput( 'action %s not in %s' % (action, ', '.join(LAPOSTE_ACTIONS))) api = LaposteApi() if not api.validate(api_input): _logger.warning('Laposte api call exception:') raise InvalidApiInput( {'api_call_exception': api.errors(api_input)}) data = api.normalize(api_input) data['service']['labelFormat'] = self.lookup_label_format( data['service']['labelFormat']) env = Environment( loader=PackageLoader('roulier', '/carriers/laposte/templates'), extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'], autoescape=True) template = env.get_template("laposte_%s.xml" % action) return { "body": template.render( service=data['service'], parcel=data['parcels'][0], auth=data['auth'], sender_address=data['from_address'], receiver_address=data['to_address'], customs=data['customs']), "headers": data['auth'], "output_format": data['service']['labelFormat'] }
def soap_wrap(self, body, headers): """Wrap body in a soap:Enveloppe.""" env = Environment( loader=PackageLoader('roulier', '/carriers/laposte/templates'), extensions=['jinja2.ext.with_']) template = env.get_template("laposte_soap.xml") body_stripped = remove_empty_tags(body) data = template.render(body=body_stripped) return data.encode('utf8')
def soap_wrap(self, body, auth): """Wrap body in a soap:Enveloppe.""" env = Environment( loader=PackageLoader('roulier', '/carriers/geodis/templates'), extensions=['jinja2.ext.with_']) template = env.get_template("geodis_soap.xml") body_stripped = remove_empty_tags(body) header_template = env.get_template("geodis_header.xml") header_xml = header_template.render(auth=auth) data = template.render(body=body_stripped, header=header_xml) return data.encode('utf8')
def encode(self, api_input, action): """Transform input to geodis compatible xml.""" if not (action in GEODIS_ACTIONS): raise InvalidApiInput( 'action %s not in %s' % (action, ', '.join(GEODIS_ACTIONS))) api = GeodisApiWs() if not api.validate(api_input): raise InvalidApiInput( 'Input error : %s' % api.errors(api_input)) data = api.normalize(api_input) data['service']['labelFormat'] = self.lookup_label_format( data['service']['labelFormat']) data['service']['shippingDate'] = data['service']['shippingDate'].replace('/','') data['from_address']['departement'] = data['from_address']['zip'][:2] is_test = data['service']['is_test'] env = Environment( loader=PackageLoader('roulier', '/carriers/geodis/templates'), extensions=['jinja2.ext.with_', 'jinja2.ext.autoescape'], autoescape=True) template = env.get_template("geodis_%s.xml" % action) return { "body": template.render( service=data['service'], parcels=data['parcels'], sender_address=data['from_address'], receiver_address=data['to_address']), "headers": data['auth'], "is_test": is_test, "output_format": api_input['service']['labelFormat'] }
def soap_wrap(self, body, auth): """Wrap body in a soap:Enveloppe.""" env = Environment( loader=PackageLoader('roulier', '/carriers/dpd/templates'), extensions=['jinja2.ext.with_']) template = env.get_template("dpd_soap.xml") body_stripped = remove_empty_tags(body) header_template = env.get_template("dpd_header.xml") header_xml = header_template.render(auth=auth) data = template.render(body=body_stripped, header=header_xml) return data.encode('utf8')
def remove_empty_tags(xml, ouput_as_string=True): """Remove empty tags with xslt transformation. param: xml a string or a etree type return: unicode string or lxml.etree._XSLTResultTree """ # use Jinja env for getting the path of template file # pkg_resouces may be an alternative, but we already # have Jinja env = Environment( loader=PackageLoader('roulier', 'templates'), extensions=['jinja2.ext.with_']) template = env.get_template("remove_empty_tags.xsl") xsl = etree.parse(open(template.filename)) transform = etree.XSLT(xsl) if isinstance(xml, basestring): xml = etree.fromstring(xml) # else we asume xml is an lxml.etree if ouput_as_string: return unicode(transform(xml)) else: return transform(xml)
def init(loop): # setup application and extensions app = web.Application(loop=loop) setattr(app, "config", configuration) # configure jinja 2 rendering engine aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader("app", "templates")) setup_global_helpers(app) await bootstrap_dal(configuration, loop) # setup routes setup_routes(app, PROJ_ROOT) # setup middlewares app.middlewares.append(cookies_middleware) app.middlewares.append(errors_middleware) host, port = configuration.host, configuration.port return app, host, port
def _build_env(): # Ignore bandit false positive: B701:jinja2_autoescape_false # This env is not used to render content that is vulnerable to XSS. env = jinja2.Environment( # nosec loader=jinja2.PackageLoader('promenade', 'templates/include'), undefined=jinja2.StrictUndefined) env.filters['b64enc'] = _base64_encode env.filters['fill_no_proxy'] = _fill_no_proxy env.filters['yaml_safe_dump_all'] = _yaml_safe_dump_all return env
def render(template_name, extra_environments=None, **kwargs): """??? ???? jinja? ?????? :param template_name: :return: """ if extra_environments is None: extra_environments = {} default_loader = PackageLoader('dodotable', 'templates') loader = extra_environments.get( 'template_loader', default_loader) if not loader: loader = default_loader get_translations = extra_environments.get('get_translations') env = Environment(loader=loader, extensions=['jinja2.ext.i18n', 'jinja2.ext.with_'], autoescape=True) env.globals.update(extra_environments) translations = get_translations() if callable(get_translations) else None if translations is None: translations = gettext.NullTranslations() env.install_gettext_translations(translations) template = env.get_template(template_name) return template.render(**kwargs)
def __init__(self): env = Environment(loader=PackageLoader('example', 'templates')) # Cache the template so we don't have to do it again for every item. self.template = env.get_template('sitemap_template.html') # Directory where result will be stored. self.result_dir = os.path.dirname(os.path.abspath(__file__)) self.result_dir = os.path.join(self.result_dir, RESULT_DIR) self.url_count = 0
def run(self, parser, namespace, values, dest, option_string=None): """ Execution of the action. :name parser: The argument parser in use. :type parser: argparse.ArgumentParser :name namespace: The namespace for parsed args. :type namespace: argparse.Namespace :name values: Values for the action. :type values: mixed :name option_string: Option string. :type option_string: str or None :raises: subprocess.CalledProcessError """ hostfs_dirs = [] add_files = {} for item in namespace.add_file: local, host = item.split('=') hostfs_dirs.append(os.path.dirname(host)) add_files[local] = host output = util.mkdir(namespace.output) with open(os.path.sep.join([output, 'Dockerfile']), 'w') as dockerfile: loader = jinja2.PackageLoader('system_buildah') rendered = loader.load( jinja2.Environment(), 'Dockerfile.j2').render( from_base=namespace.from_base, name=values, maintainer=namespace.maintainer, license_name=namespace.license, summary=namespace.summary, version=namespace.version, help_text=namespace.help_text, architecture=namespace.architecture, scope=namespace.scope, add_files=add_files, hostfs_dirs=set(hostfs_dirs)) dockerfile.write(rendered)
def _render_service_template(self, namespace): """ Renders and returns the service template. :name namespace: The namespace for parsed args. :type namespace: argparse.Namespace :returns: Rendered template :rtype: str """ loader = jinja2.PackageLoader('system_buildah') return loader.load( jinja2.Environment(), 'service.template.j2').render( description=namespace.description)
def _render_init_template(self, namespace): """ Renders and returns the init.sh. :name namespace: The namespace for parsed args. :type namespace: argparse.Namespace :returns: Rendered template :rtype: str """ loader = jinja2.PackageLoader('system_buildah') return loader.load( jinja2.Environment(), 'init.sh.j2').render()
def _template_render(self, template, peer): ''' Get Data and render the template ''' env = Environment(loader=PackageLoader('peerme', 'templates')) template = env.get_template(template) return template.render( my_asn=self.opts.config.config['peerme']['my_asn'], peer=peer)