Python jinja2.PackageLoader() Examples
The following are 30
code examples of jinja2.PackageLoader().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
jinja2
, or try the search function
.
Example #1
Source File: bokeh.py From backtrader_plotting with GNU General Public License v3.0 | 8 votes |
def _output_plot_file(self, model, idx, filename=None, template="basic.html.j2"): if filename is None: tmpdir = tempfile.gettempdir() filename = os.path.join(tmpdir, f"bt_bokeh_plot_{idx}.html") env = Environment(loader=PackageLoader('backtrader_plotting.bokeh', 'templates')) templ = env.get_template(template) templ.globals['now'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") html = file_html(model, template=templ, resources=CDN, template_variables=dict( stylesheet=self._output_stylesheet(), show_headline=self.p.scheme.show_headline, ) ) with open(filename, 'w') as f: f.write(html) return filename
Example #2
Source File: _model_factory.py From flask-react-spa with MIT License | 6 votes |
def _load_from_yaml(self, filename): if not self.env: self.env = Environment(loader=PackageLoader('tests', 'model_fixtures')) faker = Faker() faker.seed_instance(1234) self.env.globals['faker'] = faker template = self.env.get_template(filename) fixture_data = yaml.load(template.render(), Loader=yaml.FullLoader) class_name = filename[:filename.rfind('.')] for identifier_id, data in fixture_data.items(): # FIXME check for dups self.class_name_lookup[identifier_id] = class_name self.model_fixtures[identifier_id] = data
Example #3
Source File: pycoQC_report.py From pycoQC with GNU General Public License v3.0 | 6 votes |
def _get_jinja_template(self, template_file=None): """""" # First, try to read provided configuration file if given if template_file: self.logger.debug("\tTry to load provided jinja template file") try: with open(template_file) as fp: template = jinja2.Template(fp.read()) return template except (FileNotFoundError, IOError, jinja2.exceptions.TemplateNotFound, jinja2.exceptions.TemplateSyntaxError): self.logger.debug ("\t\tFile not found, non-readable or invalid") # Last use the default harcoded config_dict self.logger.debug ("\tRead default jinja template") env = jinja2.Environment ( loader=jinja2.PackageLoader('pycoQC', 'templates'), autoescape=jinja2.select_autoescape(["html"])) template = env.get_template('spectre.html.j2') return template
Example #4
Source File: send_email.py From beans with MIT License | 6 votes |
def send_single_email(email, subject, template, template_arguments): """ Send an email using the SendGrid API Args: - email :string => the user's work email (ie username@company.com) - subject :string => the subject line for the email - template :string => the template file, corresponding to the email sent. - template_arguments :dictionary => keyword arguments to specify to render_template Returns: - SendGrid response """ load_secrets() env = Environment(loader=PackageLoader('yelp_beans', 'templates')) template = env.get_template(template) rendered_template = template.render(template_arguments) message = mail.Mail( from_email=mail.Email(SENDGRID_SENDER), subject=subject, to_email=mail.Email(email), content=Content("text/html", rendered_template) ) return send_grid_client.client.mail.send.post(request_body=message.get())
Example #5
Source File: scaffold.py From snipsmanager with MIT License | 6 votes |
def __init__(self): self.jinja_env = Environment( loader=PackageLoader('snipsmanager', 'templates')) self.wizard = Wizard() self.wizard.add_question( description="Give your skill a name. For instance: lightskill, gardeningskill, etc ...", text="Project name? ", input_function=ask_for_input, input_validation=lambda x: len(x) > 0) self.wizard.add_question(description="A short sentence to describe what your skill does.", text="Description? ", input_function=ask_for_input, input_validation=lambda x: len(x) > 0) self.wizard.add_question(description="", text="Author? ", input_function=ask_for_input, input_validation=lambda x: True) self.wizard.add_question(description="", text="Email address? ", input_function=ask_for_input, input_validation=email_is_valid, default_value=get_user_email_git())
Example #6
Source File: test.py From swagger2rst with MIT License | 6 votes |
def prepare_env(cnt, file_name=True, inline=False): this = {} if file_name: this['file_name_json'] = os.path.join(SAMPLES_PATH, '{}.json'.format(cnt)) this['file_name_rst'] = os.path.join(SAMPLES_PATH, '{}{inline}.rst'.format(cnt, inline='_inline' if inline else '') ) with codecs.open(this['file_name_json'], 'r', encoding='utf-8') as _file: doc = json.load(_file) else: this['file_name_json'] = False this['file_name_rst'] = False doc = json.load(cnt) this['swagger_doc'] = rst.SwaggerObject(doc) doc_module = importlib.import_module('swg2rst.utils.rst') jinja_env = Environment(lstrip_blocks=True, trim_blocks=True) jinja_env.loader = PackageLoader('swg2rst') for name, function in inspect.getmembers(doc_module, inspect.isfunction): jinja_env.filters[name] = function jinja_env.filters['sorted'] = sorted template = jinja_env.get_template('main.rst') this['raw_rst'] = template.render(doc=this['swagger_doc'], inline=inline) this['pattern'] = re.compile(r'[idm]_\w{32}') this['normalize'] = lambda x: x[:-1] if x[-1] == '\n' else x return this
Example #7
Source File: swagger2rst.py From swagger2rst with MIT License | 6 votes |
def prepare_template(flags, module): jinja_env = Environment(lstrip_blocks=True, trim_blocks=True) for name, function in inspect.getmembers(module, inspect.isfunction): jinja_env.filters[name] = function if flags.template: jinja_env.loader = FileSystemLoader(os.path.dirname(flags.template)) template = jinja_env.get_template(os.path.basename(flags.template)) else: jinja_env.loader = PackageLoader('swg2rst') try: template = jinja_env.get_template('main.{}'.format(flags.format)) except TemplateError as err: sys.exit(u'Template Error: {}'.format(err.message)) return template
Example #8
Source File: cli.py From slack-export-viewer with MIT License | 6 votes |
def export(archive_dir): css = pkgutil.get_data('slackviewer', 'static/viewer.css').decode('utf-8') tmpl = Environment(loader=PackageLoader('slackviewer')).get_template("export_single.html") export_file_info = get_export_info(archive_dir) r = Reader(export_file_info["readable_path"]) channel_list = sorted( [{"channel_name": k, "messages": v} for (k, v) in r.compile_channels().items()], key=lambda d: d["channel_name"] ) html = tmpl.render( css=css, generated_on=datetime.now(), workspace_name=export_file_info["workspace_name"], source_file=export_file_info["basename"], channels=channel_list ) outfile = open(export_file_info["stripped_name"] + '.html', 'w') outfile.write(html.encode('utf-8'))
Example #9
Source File: utils.py From backtrader_plotting with GNU General Public License v3.0 | 6 votes |
def generate_stylesheet(scheme, template="basic.css.j2") -> str: env = Environment(loader=PackageLoader('backtrader_plotting.bokeh', 'templates')) templ = env.get_template(template) css = templ.render(dict( datatable_row_color_even=scheme.table_color_even, datatable_row_color_odd=scheme.table_color_odd, datatable_header_color=scheme.table_header_color, tab_active_background_color=scheme.tab_active_background_color, tab_active_color=scheme.tab_active_color, tooltip_background_color=scheme.tooltip_background_color, tooltip_text_color_label=scheme.tooltip_text_label_color, tooltip_text_color_value=scheme.tooltip_text_value_color, body_background_color=scheme.body_background_color, tag_pre_background_color=scheme.tag_pre_background_color, headline_color=scheme.plot_title_text_color, text_color=scheme.text_color, ) ) return css
Example #10
Source File: bokeh_webapp.py From backtrader_plotting with GNU General Public License v3.0 | 6 votes |
def start(self, ioloop=None): """Serves a backtrader result as a Bokeh application running on a web server""" def make_document(doc: Document): if self._on_session_destroyed is not None: doc.on_session_destroyed(self._on_session_destroyed) # set document title doc.title = self._title # set document template env = Environment(loader=PackageLoader('backtrader_plotting.bokeh', 'templates')) doc.template = env.get_template(self._html_template) doc.template_variables['stylesheet'] = utils.generate_stylesheet(self._scheme) # get root model model = self._model_factory_fnc(doc) doc.add_root(model) self._run_server(make_document, ioloop=ioloop, port=self._port)
Example #11
Source File: app.py From revelation with MIT License | 6 votes |
def dispatch_request(self, request): env = Environment( loader=PackageLoader("revelation", "templates"), autoescape=select_autoescape(["html"]), ) context = { "meta": self.config.get("REVEAL_META"), "slides": self.load_slides( self.presentation, self.config.get("REVEAL_SLIDE_SEPARATOR"), self.config.get("REVEAL_VERTICAL_SLIDE_SEPARATOR"), ), "config": self.config.get("REVEAL_CONFIG"), "theme": self.get_theme(self.config.get("REVEAL_THEME")), "style": self.style, "reloader": self.reloader, } template = env.get_template("presentation.html") return Response( template.render(**context), headers={"content-type": "text/html"} )
Example #12
Source File: cli.py From qb with MIT License | 6 votes |
def slurm(partition, qos, mem_per_cpu, max_time, nodelist, cpus_per_task, luigi_module, luigi_task): env = Environment(loader=PackageLoader('qanta', 'slurm/templates')) template = env.get_template('luigi-template.sh.jinja2') sbatch_script = template.render({ 'luigi_module': luigi_module, 'luigi_task': luigi_task, 'partition': partition, 'qos': qos, 'mem_per_cpu': mem_per_cpu, 'max_time': max_time, 'nodelist': nodelist, 'cpus_per_task': cpus_per_task }) tmp_file = get_tmp_filename() with open(tmp_file, 'w') as f: f.write(sbatch_script) shell(f'sbatch {tmp_file}') shell(f'rm -f {tmp_file}')
Example #13
Source File: nso_payload.py From virlutils with MIT License | 6 votes |
def render_xml_payload(virl_xml, roster=None, interfaces=None, protocol="telnet"): """ we need to merge information from multiple sources to generate all the required parameters for the inventory """ env = Environment(loader=PackageLoader('virl'), trim_blocks=False) inventory = sim_info(virl_xml, roster=roster, interfaces=interfaces, protocol=protocol) # pass all available data to template for rendering, this can probably be # pruned back at some point xml = env.get_template('nso/xml_payload.j2').render(inventory=inventory) return xml
Example #14
Source File: report_generator.py From qb with MIT License | 6 votes |
def create(self, variables, md_output, pdf_output): env = Environment(loader=PackageLoader('qanta', 'reporting/templates')) template = env.get_template(self.template) markdown = template.render(variables) if md_output is not None: with open(md_output, 'w') as f: f.write(markdown) try: import pypandoc pypandoc.convert_text( markdown, 'pdf', format='md', outputfile=pdf_output, extra_args=['-V', 'geometry:margin=.75in'] ) except Exception as e: log.warn('Pandoc was not installed or there was an error calling it, omitting PDF report') log.warn(str(e))
Example #15
Source File: ansible_inventory.py From virlutils with MIT License | 6 votes |
def render_ini_inventory(virl_xml, roster=None, interfaces=None): """ we need to merge information from multiple sources to generate all the required parameters for the inventory """ j2_env = Environment(loader=PackageLoader('virl'), trim_blocks=False) inventory = generate_inventory_dict(virl_xml, roster=roster, interfaces=interfaces) # pass all available data to template for rendering, this can probably # be pruned back at some point template = j2_env.get_template('ansible/inventory_ini_template.j2') return template.render(inventory=inventory)
Example #16
Source File: redmine_issue_updater.py From redmine2github with MIT License | 6 votes |
def __init__(self, redmine_server, redmine_api_key, project_name_or_identifier, issues_dirname, redmine2github_id_map_filename): """ Constructor :param redmine_server: str giving the url of the redmine server. e.g. https://redmine.myorg.edu/ :param redmine_api_key: str with a redmine api key :param project_name_or_identifier: str or int with either the redmine project id or project identifier :param issues_base_directory: str, directory to download the redmine issues in JSON format. Directory will be crated """ self.redmine_server = redmine_server self.redmine_api_key = redmine_api_key self.project_name_or_identifier = project_name_or_identifier self.issue_dirname = issues_dirname msg('redmine2github_id_map_filename: %s' % redmine2github_id_map_filename) self.redmine2github_id_map = json.loads(open(redmine2github_id_map_filename, 'rU').read()) self.redmine_conn = None self.redmine_project = None self.jinja_env = Environment(loader=PackageLoader('redmine_ticket', 'templates')) self.setup()
Example #17
Source File: config.py From calm-dsl with Apache License 2.0 | 6 votes |
def _render_config_template( ip, port, username, password, project_name, log_level, schema_file="config.ini.jinja2", ): """renders the config template""" loader = PackageLoader(__name__, "") env = Environment(loader=loader) template = env.get_template(schema_file) text = template.render( ip=ip, port=port, username=username, password=password, project_name=project_name, log_level=log_level, ) return text.strip() + os.linesep
Example #18
Source File: jinja2.py From watson-framework with BSD 3-Clause "New" or "Revised" License | 6 votes |
def register_loaders(self, application=None): user_path_loaders = [jinja2.FileSystemLoader(path) for path in self.config.get('paths')] user_package_loaders = [jinja2.PackageLoader(*package) for package in self.config.get('packages')] user_loaders = user_package_loaders + user_path_loaders system_loaders = [jinja2.PackageLoader(*package) for package in self.config.get('framework_packages')] if self._debug_mode: loaders = system_loaders + user_loaders else: loaders = user_loaders + system_loaders kwargs = self.config.get('environment', {}) loader = jinja2.ChoiceLoader(loaders) kwargs['loader'] = loader self._choice_loader = loader self._env = jinja2.Environment(**kwargs) self._env.application = application
Example #19
Source File: __init__.py From pascal-voc-writer with MIT License | 6 votes |
def __init__(self, path, width, height, depth=3, database='Unknown', segmented=0): environment = Environment(loader=PackageLoader('pascal_voc_writer', 'templates'), keep_trailing_newline=True) self.annotation_template = environment.get_template('annotation.xml') abspath = os.path.abspath(path) self.template_parameters = { 'path': abspath, 'filename': os.path.basename(abspath), 'folder': os.path.basename(os.path.dirname(abspath)), 'width': width, 'height': height, 'depth': depth, 'database': database, 'segmented': segmented, 'objects': [] }
Example #20
Source File: hpp2plantuml.py From hpp2plantuml with MIT License | 6 votes |
def __init__(self, template_file=None, flag_dep=False): """Constructor The `Diagram` class constructor simply initializes object lists. It does not create objects or relationships. """ self._flag_dep = flag_dep self.clear() loader_list = [] if template_file is not None: loader_list.append(jinja2.FileSystemLoader( os.path.abspath(os.path.dirname(template_file)))) self._template_file = os.path.basename(template_file) else: self._template_file = 'default.puml' loader_list.append(jinja2.PackageLoader('hpp2plantuml', 'templates')) self._env = jinja2.Environment(loader=jinja2.ChoiceLoader( loader_list), keep_trailing_newline=True)
Example #21
Source File: project.py From cloudformation-cli with Apache License 2.0 | 6 votes |
def __init__(self, overwrite_enabled=False, root=None): self.overwrite_enabled = overwrite_enabled self.root = Path(root) if root else Path.cwd() self.settings_path = self.root / SETTINGS_FILENAME self.type_info = None self.language = None self._plugin = None self.settings = None self.schema = None self.runtime = "noexec" self.entrypoint = None self.test_entrypoint = None self.env = Environment( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True, loader=PackageLoader(__name__, "templates/"), autoescape=select_autoescape(["html", "htm", "xml", "md"]), ) self.env.filters["escape_markdown"] = escape_markdown LOG.debug("Root directory: %s", self.root)
Example #22
Source File: base.py From calm-dsl with Apache License 2.0 | 6 votes |
def _init(cls): if cls.package_name is None: raise NotImplementedError("Package name not given") if cls.spec_template_file is None: raise NotImplementedError("Spec file not given") loader = PackageLoader(cls.package_name, "") env = Environment(loader=loader) template = env.get_template(cls.spec_template_file) tdict = yaml.safe_load(StringIO(template.render())) tdict = jsonref.loads(json.dumps(tdict)) # TODO - Check if keys are present cls.provider_spec = tdict["components"]["schemas"]["provider_spec"] cls.Validator = StrictDraft7Validator(cls.provider_spec)
Example #23
Source File: report.py From arche with MIT License | 5 votes |
def __init__(self): self.results: Dict[str, Result] = {} self.env = Environment( loader=PackageLoader("arche", "templates"), autoescape=select_autoescape(["html"]), extensions=["jinja2.ext.loopcontrols"], ) self.env.filters["linkify"] = linkify
Example #24
Source File: jinja2.py From watson-framework with BSD 3-Clause "New" or "Revised" License | 5 votes |
def searched_paths(self): paths = [] for loader in self.loader.loaders: if isinstance(loader, jinja2.FileSystemLoader): paths += loader.searchpath elif isinstance(loader, jinja2.PackageLoader): paths.append(loader.provider.module_path) return sorted(paths)
Example #25
Source File: ext_jinja2.py From jdcloud-cli with Apache License 2.0 | 5 votes |
def render(self, data_dict, template=None, **kw): """ Take a data dictionary and render it using the given template file. Additional keyword arguments are ignored. Required Arguments: :param data_dict: The data dictionary to render. :keyword template: The path to the template, after the ``template_module`` or ``template_dirs`` prefix as defined in the application. :returns: str (the rendered template text) """ LOG.debug("rendering output using '%s' as a template." % template) content, _type, path = self.load_template_with_location(template) if _type == 'directory': self.env.loader = FileSystemLoader(self.app._meta.template_dirs) elif _type == 'module': parts = self.app._meta.template_module.rsplit('.', 1) self.env.loader = PackageLoader(parts[0], package_path=parts[1]) if sys.version_info[0] >= 3: if not isinstance(content, str): content = content.decode('utf-8') else: if not isinstance(content, unicode): # pragma: nocover # noqa content = content.decode('utf-8') # pragma: nocover tmpl = self.env.from_string(content) return tmpl.render(**data_dict)
Example #26
Source File: renderer.py From promenade with Apache License 2.0 | 5 votes |
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 env.filters['toyaml'] = _yaml_safe_dump_arg return env
Example #27
Source File: transcribe.py From kraken with Apache License 2.0 | 5 votes |
def __init__(self, font=None, font_style=None): logging.info('Initializing transcription object.') logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), autoescape=True) logger.debug('Loading transcription template.') self.tmpl = env.get_template('layout.html') self.pages = [] # type: List[dict] self.font = {'font': font, 'style': font_style} self.text_direction = 'horizontal-tb' self.page_idx = 1 self.line_idx = 1 self.seg_idx = 1
Example #28
Source File: sdk_helpers.py From resilient-python-api with MIT License | 5 votes |
def setup_jinja_env(relative_path_to_templates): """ Returns a Jinja2 Environment with Jinja templates found in resilient_sdk/<<relative_path_to_templates>> """ jinja_env = Environment( loader=PackageLoader("resilient_sdk", relative_path_to_templates), # Loads Jinja Templates in resilient_sdk/<<relative_path_to_templates>> trim_blocks=True, # First newline after a block is removed lstrip_blocks=True, # Leading spaces and tabs are stripped from the start of a line to a block keep_trailing_newline=True # Preserve the trailing newline when rendering templates ) # Add custom filters to our jinja_env add_filters_to_jinja_env(jinja_env) return jinja_env
Example #29
Source File: api.py From dp-agent with Apache License 2.0 | 5 votes |
def init_app(agent, session, consumers, logger_stats, output_formatter, debug=False, response_time_limit=0): app = web.Application() handler = ApiHandler(output_formatter, response_time_limit) pages = PagesHandler(debug) stats = WSstatsHandler() chat = WSChatHandler(output_formatter) consumers = [asyncio.ensure_future(i.call_service(agent.process)) for i in consumers] async def on_startup(app): app['consumers'] = consumers app['agent'] = agent app['client_session'] = session app['websockets'] = [] app['logger_stats'] = logger_stats asyncio.ensure_future(agent.state_manager.prepare_db()) async def on_shutdown(app): for c in app['consumers']: c.cancel() if app['client_session']: await app['client_session'].close() tasks = asyncio.all_tasks() for task in tasks: task.cancel() app.router.add_post('', handler.handle_api_request) app.router.add_get('/api/dialogs/{dialog_id}', handler.dialog) app.router.add_get('/api/user/{user_telegram_id}', handler.dialogs_by_user) app.router.add_get('/ping', pages.ping) app.router.add_get('/debug/current_load', stats.ws_page) app.router.add_get('/debug/current_load/ws', stats.ws_handler) app.router.add_get('/chat', chat.ws_page) app.router.add_get('/chat/ws', chat.ws_handler) app.on_startup.append(on_startup) app.on_shutdown.append(on_shutdown) aiohttp_jinja2.setup(app, loader=jinja2.PackageLoader('deeppavlov_agent.http_api', 'templates')) return app
Example #30
Source File: __init__.py From ob2 with BSD 2-Clause "Simplified" License | 5 votes |
def get_jinja_environment(): global jinja_environment if jinja_environment is None: jinja_environment = Environment(loader=PackageLoader("ob2.mailer", "templates")) jinja_environment.globals.update(JINJA_EXPORTS) jinja_environment.globals["url_for"] = url_for return jinja_environment