Python jinja2.FileSystemLoader() Examples

The following are 30 code examples of jinja2.FileSystemLoader(). 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: malss.py    From malss with MIT License 8 votes vote down vote up
def generate_module_sample(self, fname='module_sample.py'):
        """
        Generate a module sample to be able to add in the model
        in your system for prediction.

        Parameters
        ----------
        fname : string (default="module_sample.py")
            A string containing a path to a output file.
        """

        env = Environment(
            loader=FileSystemLoader(
                os.path.abspath(
                    os.path.dirname(__file__)) + '/template', encoding='utf8'))
        tmpl = env.get_template('sample_code.py.tmp')
        encoded = True if len(self.data.del_columns) > 0 else False
        html = tmpl.render(algorithm=self.algorithms[self.best_index],
                           encoded=encoded,
                           standardize=self.standardize).encode('utf-8')
        fo = io.open(fname, 'w', encoding='utf-8')
        fo.write(html.decode('utf-8'))
        fo.close() 
Example #2
Source File: get.py    From genielibs with Apache License 2.0 7 votes vote down vote up
def get_jinja_template(templates_dir, template_name):
    """ Gets the jinja template specified

        Args:
            templates_dir ('str'): Templates directory
            template_name ('str'): Template name

        Returns:
            ('obj') jinja template
            None

        Raises:
            None
    """
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(searchpath=templates_dir),
        undefined=jinja2.StrictUndefined
    )

    try:
        template = env.get_template(template_name)
    except TemplateNotFound:
        return

    return template 
Example #3
Source File: get.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def load_jinja_template(path, file, **kwargs):
    """Use Jinja templates to build the device configuration

        Args:
            path (`str`): Path to file directory
            file (`str`): File name
            kwargs (`dict`): Key value pairs
        Returns:
            out (`str`): Rendered template
    """
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=path))

    template = env.get_template(file)
    out = template.render(**kwargs)

    return out 
Example #4
Source File: hpp2plantuml.py    From hpp2plantuml with MIT License 6 votes vote down vote up
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 #5
Source File: app_svc.py    From caldera with Apache License 2.0 6 votes vote down vote up
def load_plugins(self, plugins):
        def trim(p):
            if p.startswith('.'):
                return False
            return True

        async def load(p):
            plugin = Plugin(name=p)
            if plugin.load_plugin():
                await self.get_service('data_svc').store(plugin)
            if plugin.name in self.get_config('plugins'):
                await plugin.enable(self.get_services())
                self.log.debug('Enabled plugin: %s' % plugin.name)
                if not plugin.version:
                    self._errors.append(Error(plugin.name, 'plugin code is not a release version'))

        for plug in filter(trim, plugins):
            if not os.path.isdir('plugins/%s' % plug) or not os.path.isfile('plugins/%s/hook.py' % plug):
                self.log.error('Problem locating the "%s" plugin. Ensure code base was cloned recursively.' % plug)
                exit(0)
            asyncio.get_event_loop().create_task(load(plug))

        templates = ['plugins/%s/templates' % p.lower() for p in self.get_config('plugins')]
        templates.append('templates')
        aiohttp_jinja2.setup(self.application, loader=jinja2.FileSystemLoader(templates)) 
Example #6
Source File: __init__.py    From flask-ponywhoosh with MIT License 6 votes vote down vote up
def init_app(self, app):
    """Initializes the App.

    Args:
        app (TYPE): Description

    Returns:
        TYPE: Description
    """

    config = app.config.copy()
    self.debug        = config.get('PONYWHOOSH_DEBUG', self.debug)
    self.indexes_path = config.get('PONYWHOOSH_INDEXES_PATH',  self.indexes_path)
    self.search_string_min_len = config.get('PONYWHOOSH_MIN_STRING_LEN', self.search_string_min_len)
    self.template_path  = config.get('PONYWHOOSH_TEMPLATE_PATH', self.template_path)
    self.url_route      = config.get('PONYWHOOSH_URL_ROUTE', self.url_route)
    self.writer_timeout = config.get('PONYWHOOSH_WRITER_TIMEOUT', self.writer_timeout)

    if self.debug:
      print('PONYWHOOSH_DEBUG: ', self.debug)
      print('PONYWHOOSH_INDEXES_PATH : ', self.indexes_path)
      print('PONYWHOOSH_MIN_STRING_LEN : ', self.search_string_min_len)
      print('PONYWHOOSH_TEMPLATE_PATH: ', self.template_path)
      print('PONYWHOOSH_URL_ROUTE: ',  self.url_route)
      print('PONYWHOOSH_WRITER_TIMEOUT: ', self.writer_timeout)

    loader = jinja2.ChoiceLoader([
        app.jinja_loader
      , jinja2.FileSystemLoader(self.template_path)
    ])

    app.jinja_loader = loader
    app.add_url_rule(
        self.url_route
      , view_func=IndexView.as_view(self.url_route
        , pw=self
        , action_url_form=self.url_route
        )
    ) 
Example #7
Source File: conf.py    From mdentropy with MIT License 6 votes vote down vote up
def render_publications():
    from jinja2 import FileSystemLoader, Environment
    sys.path.append('.')
    import bibparse

    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('publications_templ.rst')

    with open('publications.bib') as f:
        bib = f.read()

    if len(bib) == 0:
        return False

    pubs = bibparse.entries.parseString(bib)
    # Reverse chronological order
    pubs = sorted(pubs, key=lambda x: -int(x.fields['year']))

    with open('publications.rst', 'w') as f:
        f.write(template.render(publications=pubs))
    return True 
Example #8
Source File: template.py    From vj4 with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: malss.py    From malss with MIT License 6 votes vote down vote up
def __make_report_supervised(self, dname):
        if not os.path.exists(dname):
            os.mkdir(dname)

        self.__plot_learning_curve(dname)

        env = Environment(
            loader=FileSystemLoader(
                os.path.abspath(
                    os.path.dirname(__file__)) + '/template', encoding='utf8'))
        if self.lang == 'jp':
            tmpl = env.get_template('report_jp.html.tmp')
        else:
            tmpl = env.get_template('report.html.tmp')

        html = tmpl.render(algorithms=self.algorithms,
                           scoring=self.scoring_name,
                           task=self.task,
                           data=self.data).encode('utf-8')
        fo = io.open(dname + '/report.html', 'w', encoding='utf-8')
        fo.write(html.decode('utf-8'))
        fo.close() 
Example #10
Source File: verify.py    From platform with GNU General Public License v3.0 6 votes vote down vote up
def generate_file_jinja(from_path, to_path, variables):
    from_path_dir, from_path_filename = split(from_path)
    loader = jinja2.FileSystemLoader(searchpath=from_path_dir)

    env_parameters = dict(
        loader=loader,
        # some files like udev rules want empty lines at the end
        # trim_blocks=True,
        # lstrip_blocks=True,
        undefined=jinja2.StrictUndefined
    )
    environment = jinja2.Environment(**env_parameters)
    template = environment.get_template(from_path_filename)
    output = template.render(variables)
    to_path_dir = dirname(to_path)
    if not isdir(to_path_dir):
        makedirs(to_path_dir)
    with open(to_path, 'wb+') as fh:
        fh.write(output.encode("UTF-8")) 
Example #11
Source File: gen.py    From platform with GNU General Public License v3.0 6 votes vote down vote up
def generate_file_jinja(from_path, to_path, variables, variable_tags=('{{', '}}')):
    from_path_dir, from_path_filename = split(from_path)
    loader = jinja2.FileSystemLoader(searchpath=from_path_dir)
    variable_start_tag, variable_end_tag = variable_tags
    env_parameters = dict(
        loader=loader,
        # some files like udev rules want empty lines at the end
        # trim_blocks=True,
        # lstrip_blocks=True,
        undefined=jinja2.StrictUndefined,
        variable_start_string=variable_start_tag,
        variable_end_string=variable_end_tag
    )
    environment = jinja2.Environment(**env_parameters)
    template = environment.get_template(from_path_filename)
    output = template.render(variables)
    to_path_dir = dirname(to_path)
    if not isdir(to_path_dir):
        makedirs(to_path_dir)
    with open(to_path, 'wb+') as fh:
        fh.write(output.encode("UTF-8")) 
Example #12
Source File: deploy.py    From picoCTF with MIT License 6 votes vote down vote up
def template_file(in_file_path, out_file_path, **kwargs):
    """
    Templates the given file with the keyword arguments.

    Args:
        in_file_path: The path to the template
        out_file_path: The path to output the templated file
        **kwargs: Variables to use in templating
    """

    env = Environment(
        loader=FileSystemLoader(os.path.dirname(in_file_path)),
        keep_trailing_newline=True,
    )
    template = env.get_template(os.path.basename(in_file_path))
    output = template.render(**kwargs)

    with open(out_file_path, "w") as f:
        f.write(output) 
Example #13
Source File: conftest.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def app_with_mail(app):
    """App with email test templates."""
    app.register_blueprint(
        Blueprint(
            "invenio_app_ils_tests", __name__,
            template_folder="templates"
        )
    )
    # add extra test templates to the search app blueprint, to fake the
    # existence of `invenio-theme` base templates.
    test_templates_path = os.path.join(os.path.dirname(__file__), "templates")
    enhanced_jinja_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(test_templates_path),
    ])
    # override default app jinja_loader to add the new path
    app.jinja_loader = enhanced_jinja_loader
    yield app 
Example #14
Source File: nq_browser.py    From natural-questions with Apache License 2.0 6 votes vote down vote up
def __init__(self, web_path, examples):
    """
    """
    tmpl_path = web_path + '/templates'
    static_path = web_path + '/static'
    jinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(tmpl_path))

    self.application = tornado.wsgi.WSGIApplication([
        (r'/', MainHandler, {
            'jinja2_env': jinja2_env,
            'examples': examples
        }),
        (r'/html', HtmlHandler, {
            'examples': examples
        }),
        (r'/features', FeaturesHandler, {
            'jinja2_env': jinja2_env,
            'examples': examples
        }),
        (r'/static/(.*)', tornado.web.StaticFileHandler, {
            'path': static_path
        }),
    ]) 
Example #15
Source File: grpc_dialout.py    From catalyst9k-network-automation with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def configure_grpc_subscription(netconf_handler, proc_subid, proc_triggertype, proc_period, proc_xpath, proc_dstaddr, proc_dstport, proc_srcaddr, proc_srcvrf):

  file_loader = FileSystemLoader('templates')

  env = Environment(loader=file_loader)

  template = env.get_template('grpc_template.j2')
  
  flow_record_payload = template.render(grpc_subid=proc_subid, grpc_trigger_type= proc_triggertype, grpc_period=proc_period, grpc_xpath=proc_xpath, grpc_dstaddr=proc_dstaddr, grpc_dstport=proc_dstport, grpc_srcaddr=proc_srcaddr, grpc_srcvrf=proc_srcvrf)

  netconf_reply = xml.dom.minidom.parseString(str(netconf_handler.edit_config(flow_record_payload, target='running')))
  print (netconf_reply.toprettyxml( indent = "  " ))
  if "<ok/>" in (netconf_reply.toprettyxml(indent = "  ")):
    return_val = True
  else:
    return_val = False

  return return_val 
Example #16
Source File: utils.py    From sniffer with Apache License 2.0 6 votes vote down vote up
def render(template_path, context):
    """
    Assuming a template at /some/path/my_tpl.html, containing:

    Hello {{ firstname }} {{ lastname }}!

    >> context = {
    'firstname': 'John',
    'lastname': 'Doe'
    }
    >> result = render('/some/path/my_tpl.html', context)
    >> print(result)
    Hello John Doe!
    """

    path, filename = opath.split(template_path)
    return jinja2.Environment(
        loader=jinja2.FileSystemLoader(path or './')
    ).get_template(filename).render(context) 
Example #17
Source File: util.py    From octavia with Apache License 2.0 6 votes vote down vote up
def install_netns_systemd_service():
    os_utils = osutils.BaseOS.get_os_util()

    flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
    # mode 00644
    mode = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)

    # TODO(bcafarel): implement this for other init systems
    # netns handling depends on a separate unit file
    netns_path = os.path.join(consts.SYSTEMD_DIR,
                              consts.AMP_NETNS_SVC_PREFIX + '.service')

    jinja_env = jinja2.Environment(
        autoescape=True, loader=jinja2.FileSystemLoader(os.path.dirname(
            os.path.realpath(__file__)
        ) + consts.AGENT_API_TEMPLATES))

    if not os.path.exists(netns_path):
        with os.fdopen(os.open(netns_path, flags, mode), 'w') as text_file:
            text = jinja_env.get_template(
                consts.AMP_NETNS_SVC_PREFIX + '.systemd.j2').render(
                    amphora_nsname=consts.AMPHORA_NAMESPACE,
                    HasIFUPAll=os_utils.has_ifup_all())
            text_file.write(text) 
Example #18
Source File: main.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def init(loop):
    # load config from yaml file
    conf = load_config(str(PROJ_ROOT / 'config' / 'dev.yml'))

    # setup application and extensions
    app = web.Application(loop=loop)
    pg = await setup_pg(app, conf, loop)

    # init modules
    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT)))

    admin = setup_admin(app, pg)
    app.add_subapp('/admin/', admin)

    # setup views and routes
    handler = SiteHandler(pg)
    add_route = app.router.add_route
    add_route('GET', '/', handler.index)
    app.router.add_static('/static', path=str(PROJ_ROOT / 'static'))

    host, port = conf['host'], conf['port']
    return app, host, port 
Example #19
Source File: main.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def init(loop):
    # load config from yaml file
    conf = load_config(str(PROJ_ROOT / 'config' / 'dev.yml'))

    # setup application and extensions
    app = web.Application(loop=loop)
    pg = await setup_pg(app, conf, loop)

    # init modules
    aiohttp_jinja2.setup(
        app, loader=jinja2.FileSystemLoader(str(TEMPLATES_ROOT))
    )

    setup_admin(app, pg)

    # setup views and routes
    handler = SiteHandler(pg)
    add_route = app.router.add_route
    add_route('GET', '/', handler.index)
    app.router.add_static('/static', path=str(PROJ_ROOT / 'static'))

    host, port = conf['host'], conf['port']
    return app, host, port 
Example #20
Source File: __init__.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def setup(app, admin_conf_path, *, resources, static_folder=None,
          template_folder=None, template_name=None, name=None,
          app_key=APP_KEY):

    admin = web.Application(loop=app.loop)
    app[app_key] = admin

    tf = gather_template_folders(template_folder)
    loader = jinja2.FileSystemLoader(tf)
    aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)

    template_name = template_name or 'admin.html'
    admin_handler = AdminHandler(admin, resources=resources, name=name,
                                 template=template_name, loop=app.loop)

    admin['admin_handler'] = admin_handler
    admin['layout_path'] = admin_conf_path

    static_folder = static_folder or str(PROJ_ROOT / 'static')
    setup_admin_handlers(admin, admin_handler, static_folder, admin_conf_path)
    return admin 
Example #21
Source File: layout_utils.py    From aiohttp_admin with Apache License 2.0 6 votes vote down vote up
def generate_config(entities, base_url, template_name=None,
                    template_folder=None, desc=None, extra_context=None):
    template_name = template_name or 'config.j2'
    desc = desc or 'aiohttp_admin'

    if all(isinstance(ent[2], sa.Table) for ent in entities):
        build_entity = table_entity
    else:
        build_entity = trafaret_entity

    context = {
        "admin_description": desc,
        "base_url": base_url if base_url.endswith("/") else base_url + '/',
        "entities": [build_entity(n, pk, s) for n, pk, s in entities],
        "extra_context": extra_context,
    }

    tf = gather_template_folders(template_folder)
    loader = jinja2.FileSystemLoader(tf)
    env = jinja2.Environment(loader=loader)
    template = env.get_template(template_name)

    text = template.render(context)
    return text 
Example #22
Source File: make_conf.py    From airflow-docker with Apache License 2.0 6 votes vote down vote up
def create_airflow_cfg(path, tpl, filename='airflow.cfg', encoding='utf8'):
    """
    create airflow.cfg
    :param path: root path
    :param tpl: template file
    :param filename: output filename
    :param encoding: Encoding(default:utf8)
    """
    env = Environment(loader=FileSystemLoader(path, encoding=encoding))
    cfg_tpl = env.get_template(tpl)
    cfg = cfg_tpl.render({env: os.environ.get(env) for env in ENVIRONMENTS})
    file_path = '/'.join([path, filename])
    if os.path.exists(file_path):
        os.remove(file_path)

    with open(file_path, 'w', encoding=encoding) as f:
        f.write(cfg)
        f.close() 
Example #23
Source File: view.py    From Bast with MIT License 6 votes vote down vote up
def render_template(self, template_name, **kwargs):
        template_dir = os.environ['TEMPLATE_FOLDER']

        env = Environment(loader=FileSystemLoader(template_dir))

        env.globals['css'] = css
        env.globals['script'] = script

        self.dict_object.update(**kwargs)

        try:
            template = env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)
        content = template.render(self.dict_object)
        return content 
Example #24
Source File: dspl2-pretty-print.py    From dspl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _RenderLocalDspl2(path, rdf):
  template_dir = Path(dspl2.__file__).parent / 'templates'
  env = jinja2.Environment(loader=jinja2.FileSystemLoader(
      template_dir.as_posix()))
  try:
    print("Loading template")
    template = env.get_template('display.html')
    print("Loading DSPL2")
    getter = dspl2.LocalFileGetter(path)
    print("Expanding DSPL2")
    if rdf:
      graph = dspl2.Dspl2RdfExpander(getter).Expand()
      print("Framing DSPL2")
      json_val = dspl2.FrameGraph(graph)
    else:
      json_val = dspl2.Dspl2JsonLdExpander(getter).Expand()
    print("Rendering template")
    return template.render(**dspl2.JsonToKwArgsDict(json_val))
  except Exception as e:
    raise
    template = loader.load(env, 'error.html')
    return template.render(action="processing",
                           url=path,
                           text=str(type(e)) + ": " + str(e)) 
Example #25
Source File: jinja_utils.py    From pybel with MIT License 6 votes vote down vote up
def build_template_environment(here: str):
    """Build a custom templating environment so Flask apps can get data from lots of different places.

    :param here: Give this the result of :code:`os.path.dirname(os.path.abspath(__file__))`
    :rtype: jinja2.Environment
    """
    from jinja2 import Environment, FileSystemLoader

    loader = FileSystemLoader(os.path.join(here, 'templates'))
    environment = Environment(
        autoescape=True,
        loader=loader,
        trim_blocks=False,
    )
    environment.globals['STATIC_PREFIX'] = here + '/static/'
    return environment 
Example #26
Source File: get.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def load_jinja_template(path, file, **kwargs):
    """Use Jinja templates to build the device configuration

        Args:
            path (`str`): Path to file directory
            file (`str`): File name
            kwargs (`dict`): Key value pairs
        Returns:
            out (`str`): Rendered template
    """
    env = jinja2.Environment(loader=jinja2.FileSystemLoader(searchpath=path))

    template = env.get_template(file)
    out = template.render(**kwargs)

    return out 
Example #27
Source File: get.py    From genielibs with Apache License 2.0 6 votes vote down vote up
def get_jinja_template(templates_dir, template_name):
    """ Gets the jinja template specified

        Args:
            templates_dir ('str'): Templates directory
            template_name ('str'): Template name

        Returns:
            ('obj') jinja template
            None

        Raises:
            None
    """
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(searchpath=templates_dir),
        undefined=jinja2.StrictUndefined
    )

    try:
        template = env.get_template(template_name)
    except TemplateNotFound:
        return

    return template 
Example #28
Source File: emailer.py    From oadoi with MIT License 6 votes vote down vote up
def create_email(address, subject, template_name, context, attachment_filenames):
    templateLoader = jinja2.FileSystemLoader(searchpath="templates")
    templateEnv = jinja2.Environment(loader=templateLoader)
    html_template = templateEnv.get_template(template_name + ".html")

    html_to_send = html_template.render(context)
    content = Content("text/html", html_to_send)

    support_email = Email("support@unpaywall.org", "Unpaywall Team")
    to_email = Email(address)

    email = Mail(support_email, subject, to_email, content)
    personalization = Personalization()
    personalization.add_to(to_email)
    # personalization.add_to(support_email)
    email.add_personalization(personalization)

    logger.info((u'sending email "{}" to {}'.format(subject, address)))
    for filename in attachment_filenames:
        email = add_results_attachment(email, filename)

    return email 
Example #29
Source File: drone_delivery.py    From dronekit-python with Apache License 2.0 5 votes vote down vote up
def __init__(self, home_coords):
        self.home_coords = home_coords
        self.options = self.get_options()
        self.environment = Environment(loader=FileSystemLoader(local_path + '/html')) 
Example #30
Source File: email.py    From PushBank2 with Apache License 2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        super(EmailPlugin, self).__init__(**kwargs)

        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '_email')
        self.template = Environment(
            loader=FileSystemLoader(path)).get_template('template.html')