Python jinja2.ChoiceLoader() Examples

The following are 30 code examples of jinja2.ChoiceLoader(). 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: __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 #2
Source File: screw_axes.py    From dials with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_html_report(self, filename):
        """Generate a html report using the data."""
        screw_axes_graphs = plot_screw_axes(self.data)
        self.data["screw_axes"] = screw_axes_graphs
        loader = ChoiceLoader(
            [
                PackageLoader("dials", "templates"),
                PackageLoader("dials", "static", encoding="utf-8"),
            ]
        )
        env = Environment(loader=loader)
        template = env.get_template("systematic_absences_report.html")
        html = template.render(
            page_title="DIALS systematic absences report",
            screw_axes_graphs=self.data["screw_axes"],
        )
        with open(filename, "wb") as f:
            f.write(html.encode("utf-8", "xmlcharrefreplace")) 
Example #3
Source File: observers.py    From dials with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_html(self, cosym_script):
        """Collect data from the individual observers and write the html."""
        filename = cosym_script.params.output.html
        if not filename:
            return
        self.data.update(CosymClusterAnalysisObserver().make_plots())
        self.data.update(UnitCellAnalysisObserver().make_plots())
        self.data.update(SymmetryAnalysisObserver().make_tables())
        print("Writing html report to: %s" % filename)
        loader = ChoiceLoader(
            [
                PackageLoader("dials", "templates"),
                PackageLoader("dials", "static", encoding="utf-8"),
            ]
        )
        env = Environment(loader=loader)
        template = env.get_template("cosym_report.html")
        html = template.render(
            page_title="DIALS cosym report",
            cosym_graphs=self.data["cosym_graphs"],
            unit_cell_graphs=self.data["unit_cell_graphs"],
            symmetry_analysis=self.data["symmetry_analysis"],
        )
        with open(filename, "wb") as f:
            f.write(html.encode("utf-8", "xmlcharrefreplace")) 
Example #4
Source File: damage_analysis.py    From dials with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_html_report(self, html_filename=None, json_filename=None):
        """Generate html report from pychef stats."""
        data = {"dose_plots": self.stats.to_dict()}
        if html_filename:
            logger.info("Writing html report to: %s", html_filename)
            loader = ChoiceLoader(
                [
                    PackageLoader("dials", "templates"),
                    PackageLoader("dials", "static", encoding="utf-8"),
                ]
            )
            env = Environment(loader=loader)
            template = env.get_template("damage_analysis_report.html")
            html = template.render(
                page_title="Damage analysis report", dose_plots=data["dose_plots"]
            )
            with open(html_filename, "wb") as f:
                f.write(html.encode("utf-8", "xmlcharrefreplace"))
        if json_filename:
            logger.info("Writing html report data to: %s", json_filename)
            with open(json_filename, "w") as outfile:
                json.dump(data, outfile) 
Example #5
Source File: core.py    From flask-ask with Apache License 2.0 6 votes vote down vote up
def init_blueprint(self, blueprint, path='templates.yaml'):
        """Initialize a Flask Blueprint, similar to init_app, but without the access
        to the application config.

        Keyword Arguments:
            blueprint {Flask Blueprint} -- Flask Blueprint instance to initialize (Default: {None})
            path {str} -- path to templates yaml file, relative to Blueprint (Default: {'templates.yaml'})
        """
        if self._route is not None:
            raise TypeError("route cannot be set when using blueprints!")

        # we need to tuck our reference to this Ask instance into the blueprint object and find it later!
        blueprint.ask = self

        # BlueprintSetupState.add_url_rule gets called underneath the covers and
        # concats the rule string, so we should set to an empty string to allow
        # Blueprint('blueprint_api', __name__, url_prefix="/ask") to result in
        # exposing the rule at "/ask" and not "/ask/".
        blueprint.add_url_rule("", view_func=self._flask_view_func, methods=['POST'])
        blueprint.jinja_loader = ChoiceLoader([YamlLoader(blueprint, path)]) 
Example #6
Source File: jinja2.py    From watson-framework with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #7
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 #8
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 #9
Source File: configure_jinja.py    From patreon-python with Apache License 2.0 5 votes vote down vote up
def configure(app):
    my_template_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(['my_site/app/views'])
    ])
    app.jinja_loader = my_template_loader
    app.jinja_env.globals.update(
        views=DependencyBubbler(views),
    ) 
Example #10
Source File: exporter.py    From Computable with MIT License 5 votes vote down vote up
def _init_environment(self, extra_loaders=None):
        """
        Create the Jinja templating environment.
        """
        here = os.path.dirname(os.path.realpath(__file__))
        loaders = []
        if extra_loaders:
            loaders.extend(extra_loaders)

        paths = self.template_path
        paths.extend([os.path.join(here, self.default_template_path),
                      os.path.join(here, self.template_skeleton_path)])
        loaders.append(FileSystemLoader(paths))

        self.environment = Environment(
            loader= ChoiceLoader(loaders),
            extensions=JINJA_EXTENSIONS
            )
        
        #Set special Jinja2 syntax that will not conflict with latex.
        if self.jinja_logic_block_start:
            self.environment.block_start_string = self.jinja_logic_block_start
        if self.jinja_logic_block_end:
            self.environment.block_end_string = self.jinja_logic_block_end
        if self.jinja_variable_block_start:
            self.environment.variable_start_string = self.jinja_variable_block_start
        if self.jinja_variable_block_end:
            self.environment.variable_end_string = self.jinja_variable_block_end
        if self.jinja_comment_block_start:
            self.environment.comment_start_string = self.jinja_comment_block_start
        if self.jinja_comment_block_end:
            self.environment.comment_end_string = self.jinja_comment_block_end 
Example #11
Source File: __init__.py    From geonotebook with Apache License 2.0 5 votes vote down vote up
def get_notebook_jinja2_loader(nbapp):
    """Return the appropriate jinja2 template loader for the notebook app.

    This is confusing but necessary to meet the following criteria:
    - Templates in geonotebook/templates will override those in core notebook
      templates
    - Core notebook templates can still be referred to/extended by referring
      to them as core@template.html

    The ChoiceLoader tries each of the loaders in turn until one of them
    provides the right template.
    The PrefixLoader allows us to refer to core templates using the core@
    prefix, this is necessary
    because we want to extend templates of the same name while referring to
    templates in a different loader (core).
    The PackageLoader lets us put our templates ahead in priority of the
    notebooks templates.
    The core_loader is last which falls back to the original loader the
    notebook uses.

    This implementation is weird, but should be compatible/composable with
    other notebook extensions and fairly future proof.

    :param nbapp: NotebookApp instance
    :returns: A jinja2 loader designed to work with our notebook templates
    :rtype: jinja2.ChoiceLoader
    """
    return ChoiceLoader([
        PrefixLoader(
            {'core': nbapp.web_app.settings['jinja2_env'].loader},
            delimiter='@'
        ),
        PackageLoader('geonotebook'),
        nbapp.web_app.settings['jinja2_env'].loader]) 
Example #12
Source File: openapi.py    From dactyl with MIT License 5 votes vote down vote up
def setup_jinja_env(self, template_path=None):
        """Sets up the environment used to inject OpenAPI data into Markdown
        templates"""
        if template_path is None:
            loader = jinja2.PackageLoader(__name__)
        else:
            logger.debug("OpenAPI spec: preferring templates from %s"%template_path)
            loader = jinja2.ChoiceLoader([
                jinja2.FileSystemLoader(template_path),
                jinja2.PackageLoader(__name__)
            ])
        self.env = jinja2.Environment(loader=loader, extensions=['jinja2.ext.i18n'])
        self.env.lstrip_blocks = True
        self.env.rstrip_blocks = True 
Example #13
Source File: dashboard.py    From NEXT with Apache License 2.0 5 votes vote down vote up
def experiment_dashboard(exp_uid, app_id):
    """
    Endpoint that renders the experiment dashboard.

    Inputs: ::\n
    	(string) exp_uid, exp_uid for a current experiment.
    """

    simple_flag = int(request.args.get('simple',0))
    force_recompute = int(request.args.get('force_recompute',1))

    if rm.get_experiment(exp_uid) is None:
        return render_template('exp_404.html', exp_uid=exp_uid), 404

    # Not a particularly good way to do this.
    alg_label_list = rm.get_algs_for_exp_uid(exp_uid)
    alg_list = [{'alg_label':alg['alg_label'],
                 'alg_label_clean':'_'.join(alg['alg_label'].split())}
                for alg in alg_label_list]

    # -- Directly use Jinja2 to load and render the app-specific dashboard template.
    env = Environment(loader=ChoiceLoader([PackageLoader('apps.{}'.format(app_id),
                                                         'dashboard'),
                                           PackageLoader('next.dashboard',
                                                         'templates')]))
    template = env.get_template('myAppDashboard.html'.format(app_id)) # looks for /next/apps/{{ app_id }}/dashboard/{{ app_id }}.html
    # The context we pass to the dashboard template.
    ctx = dict(app_id=app_id,
               exp_uid=exp_uid,
               alg_list=alg_list,
               exceptions_present=False,#exceptions_present(exp_uid),
               url_for=url_for,
               simple_flag=int(simple_flag),
               force_recompute=int(force_recompute))
    # Inject standard Flask context + context processors
    current_app.update_template_context(ctx)

    # Render the template
    return template.render(**ctx) 
Example #14
Source File: test_template.py    From gapic-generator-python with Apache License 2.0 5 votes vote down vote up
def check_template(template_fragment, expected_output, **kwargs):
    # Making a new environment for every unit test seems wasteful,
    # but the obvious alternative (make env an instance attribute
    # and passing a FunctionLoader whose load function returns
    # a constantly reassigned string attribute) isn't any faster
    # and is less clear.
    expected_output = dedent(expected_output)
    env = jinja2.Environment(
        loader=jinja2.ChoiceLoader(
            [jinja2.FileSystemLoader(
                searchpath=path.realpath(path.join(path.dirname(__file__),
                                                   "..", "..", "..",
                                                   "gapic", "templates", "examples"))),
             jinja2.DictLoader(
                 {"template_fragment": dedent(template_fragment)}),
             ]),

        undefined=jinja2.StrictUndefined,
        extensions=["jinja2.ext.do"],
        trim_blocks=True,
        lstrip_blocks=True
    )

    env.filters['snake_case'] = utils.to_snake_case
    env.filters['coerce_response_name'] = sample_utils.coerce_response_name

    template = env.get_template("template_fragment")
    text = template.render(**kwargs)
    expected_output = dedent(expected_output)

    assert text == expected_output 
Example #15
Source File: service.py    From graphql-over-kafka with MIT License 5 votes vote down vote up
def init_app(self):
        from nautilus.api.endpoints import template_dir as api_template_dir
        from nautilus.auth import template_dir as auth_template_dir
        # the secret key
        secret_key = 'NERbTdtQl7IrBM9kx1PDjJXiyZhWWBZ9E7q2B3U7KVE='
        # create a web application instance
        self.app = aiohttp.web.Application(
            middlewares=[
                session_middleware(
                    EncryptedCookieStorage(secret_key, secure=True, domain='*')
                )
            ]
        )
        # add the template loader
        aiohttp_jinja2.setup(self.app,
            loader=jinja2.ChoiceLoader([
                jinja2.FileSystemLoader(api_template_dir),
                jinja2.FileSystemLoader(auth_template_dir)
            ])
        )
        # TODO:
            # debug mode

        # attach the ioloop to the application
        self.loop = asyncio.get_event_loop()
        # attach the service to the loop
        self.loop.service = self 
Example #16
Source File: jinja2.py    From watson-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def loader(self):
        if not self._choice_loader:
            self._choice_loader = jinja2.ChoiceLoader()
        return self._choice_loader 
Example #17
Source File: generator.py    From swagger-django-generator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_to_string(backend, filename, context):
    # type: (str, str, Dict) -> str
    """
    Render a template using the specified context
    :param backend: The backend for which the template is rendered
    :param filename: The template name
    :param context: The data to use when rendering the template
    :return: The rendered template as a string
    """
    template_directory = "./swagger_django_generator/templates/{}".format(backend)
    loaders = [jinja2.FileSystemLoader(template_directory)]
    try:
        import swagger_django_generator
        loaders.append(jinja2.PackageLoader("swagger_django_generator", "templates/{}".format(backend)))
    except ImportError:
        pass

    environment = jinja2.Environment(
        loader=jinja2.ChoiceLoader(loaders),
        trim_blocks=True,
        lstrip_blocks=True,
    )
    environment.filters["clean_schema"] = clean_schema
    environment.filters["parse_array"] = parse_array

    return environment.get_template(filename).render(context) 
Example #18
Source File: handlers.py    From nativeauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _register_template_path(self):
        if self._loaded:
            return
        self.log.debug('Adding %s to template path', TEMPLATE_DIR)
        loader = FileSystemLoader([TEMPLATE_DIR])
        env = self.settings['jinja2_env']
        previous_loader = env.loader
        env.loader = ChoiceLoader([previous_loader, loader])
        self._loaded = True 
Example #19
Source File: render.py    From rdm with MIT License 5 votes vote down vote up
def _create_loader(loaders=None):
    if loaders is None:
        loaders = [
            jinja2.FileSystemLoader('.'),
        ]

    return jinja2.ChoiceLoader(loaders) 
Example #20
Source File: handlers.py    From nbgitpuller with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def initialize(self):
        super().initialize()
        # FIXME: Is this really the best way to use jinja2 here?
        # I can't seem to get the jinja2 env in the base handler to
        # actually load templates from arbitrary paths ugh.
        jinja2_env = self.settings['jinja2_env']
        jinja2_env.loader = jinja2.ChoiceLoader([
            jinja2_env.loader,
            jinja2.FileSystemLoader(
                os.path.join(os.path.dirname(__file__), 'templates')
            )
        ]) 
Example #21
Source File: template_loader.py    From zentral with Apache License 2.0 5 votes vote down vote up
def _get_j2env(self):
        if self._j2env is None:
            templates_dirs = [user_templates_dir]
            for app_name, app_config in apps.app_configs.items():
                app_events_template_dir = getattr(app_config, 'events_templates_dir', None)
                if app_events_template_dir:
                    templates_dirs.append(app_events_template_dir)
            templates_dirs.extend(self.extra_lookup_dirs)
            self._j2env = Environment(loader=ChoiceLoader([FileSystemLoader(d) for d in templates_dirs]),
                                      trim_blocks=True)
            logger.debug('Jinja2 env loaded')
        return self._j2env 
Example #22
Source File: firstuseauthenticator.py    From firstuseauthenticator with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _register_template_path(self):
        if self._loaded:
            return

        self.log.debug('Adding %s to template path', TEMPLATE_DIR)
        loader = FileSystemLoader([TEMPLATE_DIR])

        env = self.settings['jinja2_env']
        previous_loader = env.loader
        env.loader = ChoiceLoader([previous_loader, loader])

        self._loaded = True 
Example #23
Source File: dactyl_build.py    From dactyl with MIT License 4 votes vote down vote up
def setup_html_env(self):
        """
        Set up a Jinja env to load custom templates for HTML / HTML->PDF builds.
        """
        if self.strict_undefined:
            preferred_undefined = jinja2.StrictUndefined
        else:
            preferred_undefined = jinja2.ChainableUndefined

        loaderset = [jinja2.PackageLoader(__name__)]
        if "template_path" in self.config:
            loaderset.insert(0, jinja2.FileSystemLoader(self.config["template_path"]))
        env = jinja2.Environment(undefined=preferred_undefined,
                    extensions=['jinja2.ext.i18n'],
                    loader=jinja2.ChoiceLoader(loaderset))

        # Customize env: add custom tests, lstrip & trim blocks
        def defined_and_equalto(a,b):
            return env.tests["defined"](a) and env.tests["equalto"](a, b)
        env.tests["defined_and_equalto"] = defined_and_equalto
        def undefined_or_ne(a,b):
            return env.tests["undefined"](a) or env.tests["ne"](a, b)
        env.tests["undefined_or_ne"] = undefined_or_ne

        env.lstrip_blocks = True
        env.trim_blocks = True

        # Set up internationalization
        mo_file = self.target.data.get("locale_file", None)
        if mo_file:
            logger.debug("Loading strings from locale_file %s"%mo_file)
            try:
                with open(mo_file, "rb") as f:
                    tl = gettext.GNUTranslations(f)
                # TODO: add_fallback?? maybe a general config option there...
            except Exception as e:
                recoverable_error("Failed to load locale_file %s: %s" %
                                  (mo_file, e), self.config.bypass_errors,
                                  error=e)
                tl = gettext.NullTranslations()
        else:
            logger.debug("No locale_file setting found.")
            tl = gettext.NullTranslations()
        env.install_gettext_translations(tl, newstyle=True)

        self.html_env = env
        return env 
Example #24
Source File: __init__.py    From Flask-Boost with MIT License 4 votes vote down vote up
def register_jinja(app):
    """Register jinja filters, vars, functions."""
    import jinja2
    from .utils import filters, permissions, helpers

    if app.debug or app.testing:
        my_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader([
                os.path.join(app.config.get('PROJECT_PATH'), 'application/macros'),
                os.path.join(app.config.get('PROJECT_PATH'), 'application/pages')
            ])
        ])
    else:
        my_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader([
                os.path.join(app.config.get('PROJECT_PATH'), 'output/macros'),
                os.path.join(app.config.get('PROJECT_PATH'), 'output/pages')
            ])
        ])
    app.jinja_loader = my_loader

    app.jinja_env.filters.update({
        'timesince': filters.timesince
    })

    def url_for_other_page(page):
        """Generate url for pagination."""
        view_args = request.view_args.copy()
        args = request.args.copy().to_dict()
        combined_args = dict(view_args.items() + args.items())
        combined_args['page'] = page
        return url_for(request.endpoint, **combined_args)

    rules = {}
    for endpoint, _rules in iteritems(app.url_map._rules_by_endpoint):
        if any(item in endpoint for item in ['_debug_toolbar', 'debugtoolbar', 'static']):
            continue
        rules[endpoint] = [{'rule': rule.rule} for rule in _rules]

    app.jinja_env.globals.update({
        'absolute_url_for': helpers.absolute_url_for,
        'url_for_other_page': url_for_other_page,
        'rules': rules,
        'permissions': permissions
    }) 
Example #25
Source File: core.py    From flask-ask with Apache License 2.0 4 votes vote down vote up
def init_app(self, app, path='templates.yaml'):
        """Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view.

        The Ask instance is given the following configuration variables by calling on Flask's configuration:

        `ASK_APPLICATION_ID`:

            Turn on application ID verification by setting this variable to an application ID or a
            list of allowed application IDs. By default, application ID verification is disabled and a
            warning is logged. This variable should be set in production to ensure
            requests are being sent by the applications you specify.
            Default: None

        `ASK_VERIFY_REQUESTS`:

            Enables or disables Alexa request verification, which ensures requests sent to your skill
            are from Amazon's Alexa service. This setting should not be disabled in production.
            It is useful for mocking JSON requests in automated tests.
            Default: True

        `ASK_VERIFY_TIMESTAMP_DEBUG`:

            Turn on request timestamp verification while debugging by setting this to True.
            Timestamp verification helps mitigate against replay attacks. It relies on the system clock
            being synchronized with an NTP server. This setting should not be enabled in production.
            Default: False

        `ASK_PRETTY_DEBUG_LOGS`:

            Add tabs and linebreaks to the Alexa request and response printed to the debug log.
            This improves readability when printing to the console, but breaks formatting when logging to CloudWatch.
            Default: False
        """
        if self._route is None:
            raise TypeError("route is a required argument when app is not None")

        self.app = app
        
        app.ask = self

        app.add_url_rule(self._route, view_func=self._flask_view_func, methods=['POST'])
        app.jinja_loader = ChoiceLoader([app.jinja_loader, YamlLoader(app, path)]) 
Example #26
Source File: __init__.py    From learning-python with MIT License 4 votes vote down vote up
def register_jinja(app):
    """Register jinja filters, vars, functions."""
    import jinja2
    from .utils import filters, permissions, helpers

    if app.debug or app.testing:
        my_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader([
                os.path.join(app.config.get('PROJECT_PATH'), 'application/macros'),
                os.path.join(app.config.get('PROJECT_PATH'), 'application/pages')
            ])
        ])
    else:
        my_loader = jinja2.ChoiceLoader([
            app.jinja_loader,
            jinja2.FileSystemLoader([
                os.path.join(app.config.get('PROJECT_PATH'), 'output/macros'),
                os.path.join(app.config.get('PROJECT_PATH'), 'output/pages')
            ])
        ])
    app.jinja_loader = my_loader

    app.jinja_env.filters.update({
        'timesince': filters.timesince
    })

    def url_for_other_page(page):
        """Generate url for pagination."""
        view_args = request.view_args.copy()
        args = request.args.copy().to_dict()
        combined_args = dict(view_args.items() + args.items())
        combined_args['page'] = page
        return url_for(request.endpoint, **combined_args)

    rules = {}
    for endpoint, _rules in iteritems(app.url_map._rules_by_endpoint):
        if any(item in endpoint for item in ['_debug_toolbar', 'debugtoolbar', 'static']):
            continue
        rules[endpoint] = [{'rule': rule.rule} for rule in _rules]

    app.jinja_env.globals.update({
        'absolute_url_for': helpers.absolute_url_for,
        'url_for_other_page': url_for_other_page,
        'rules': rules,
        'permissions': permissions
    }) 
Example #27
Source File: template.py    From signac-flow with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def init(alias=None, template=None, root=None, out=None):
    "Initialize a templated FlowProject module."
    if alias is None:
        alias = 'project'
    elif not alias.isidentifier():
        raise ValueError(
            "The alias '{}' is not a valid Python identifier and therefore "
            "not be used as a FlowProject alias.".format(alias))
    if template is None:
        template = 'minimal'
    if out is None:
        out = sys.stderr

    if os.path.splitext(alias)[1]:
        raise RuntimeError("Please provide a name without suffix!")

    project_class_name = alias.capitalize()
    if not project_class_name.endswith('Project'):
        project_class_name += 'Project'

    template_environment = jinja2.Environment(
        loader=jinja2.ChoiceLoader([
            jinja2.FileSystemLoader('templates'),
            jinja2.PackageLoader('flow', 'templates')]),
        trim_blocks=True)

    context = dict()
    context['alias'] = alias
    context['project_class_name'] = project_class_name

    # render all templates
    codes = dict()

    for fn, fn_template in TEMPLATES[template]:
        fn_ = fn.format(alias=alias)   # some of the filenames may depend on the alias
        template = template_environment.get_template(fn_template)
        codes[fn_] = template.render(** context)

    # create files
    files_created = []
    for fn, code in codes.items():
        try:
            if root is not None:
                fn = os.path.join(root, fn)
            with open(fn, 'x') as fw:
                fw.write(code + '\n')
        except OSError as e:
            if e.errno == errno.EEXIST:
                logger.error(
                    "Error while trying to initialize flow project with alias '{alias}', "
                    "a file named '{fn}' already exists!".format(alias=alias, fn=fn))
            else:
                logger.error(
                    "Error while trying to initialize flow project with alias '{alias}': "
                    "'{error}'.".format(alias=alias, error=e))
        else:
            files_created.append(fn)
            print("Created file '{}'.".format(fn), file=out)
    return files_created 
Example #28
Source File: project.py    From signac-flow with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _setup_template_environment(self):
        """Setup the jinja2 template environment.

        The templating system is used to generate templated scripts for the script()
        and submit_operations() / submit() function and the corresponding command line
        subcommands.
        """
        if self._config.get('flow') and self._config['flow'].get('environment_modules'):
            envs = self._config['flow'].as_list('environment_modules')
        else:
            envs = []

        # Templates are searched in the local template directory first, then in additionally
        # installed packages, then in the main package 'templates' directory.
        extra_packages = []
        for env in envs:
            try:
                extra_packages.append(jinja2.PackageLoader(env, 'templates'))
            except ImportError as error:
                logger.warning("Unable to load template from package '{}'.".format(error.name))

        load_envs = ([jinja2.FileSystemLoader(self._template_dir)] +
                     extra_packages +
                     [jinja2.PackageLoader('flow', 'templates')])

        template_environment = jinja2.Environment(
            loader=jinja2.ChoiceLoader(load_envs),
            trim_blocks=True,
            extensions=[TemplateError])

        # Setup standard filters that can be used to format context variables.
        template_environment.filters['format_timedelta'] = tf.format_timedelta
        template_environment.filters['identical'] = tf.identical
        template_environment.filters['with_np_offset'] = tf.with_np_offset
        template_environment.filters['calc_tasks'] = tf.calc_tasks
        template_environment.filters['calc_num_nodes'] = tf.calc_num_nodes
        template_environment.filters['check_utilization'] = tf.check_utilization
        template_environment.filters['homogeneous_openmp_mpi_config'] = \
            tf.homogeneous_openmp_mpi_config
        template_environment.filters['get_config_value'] = flow_config.get_config_value
        template_environment.filters['require_config_value'] = flow_config.require_config_value
        template_environment.filters['get_account_name'] = tf.get_account_name
        template_environment.filters['print_warning'] = tf.print_warning
        if 'max' not in template_environment.filters:    # for jinja2 < 2.10
            template_environment.filters['max'] = max
        if 'min' not in template_environment.filters:    # for jinja2 < 2.10
            template_environment.filters['min'] = min

        return template_environment 
Example #29
Source File: convertor.py    From pyp2rpm with MIT License 4 votes vote down vote up
def convert(self):
        """Returns RPM SPECFILE.
        Returns:
            rendered RPM SPECFILE.
        """
        # move file into position
        try:
            local_file = self.getter.get()
        except (exceptions.NoSuchPackageException, OSError) as e:
            logger.error(
                "Failed and exiting:", exc_info=True)
            logger.info("Pyp2rpm failed. See log for more info.")

            sys.exit(e)

        # save name and version from the file (rewrite if set previously)
        self.name, self.version = self.getter.get_name_version()

        self.local_file = local_file
        data = self.metadata_extractor.extract_data(self.client)
        logger.debug("Extracted metadata:")
        logger.debug(pprint.pformat(data.data))
        self.merge_versions(data)

        jinja_env = jinja2.Environment(loader=jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(['/']),
            jinja2.PackageLoader('pyp2rpm', 'templates'), ]))

        for filter in filters.__all__:
            jinja_env.filters[filter.__name__] = filter

        try:
            jinja_template = jinja_env.get_template(
                os.path.abspath(self.template))
        except jinja2.exceptions.TemplateNotFound:
            # absolute path not found => search in default template dir
            logger.warning('Template: {0} was not found in {1} using default '
                           'template dir.'.format(
                               self.template, os.path.abspath(self.template)))

            jinja_template = jinja_env.get_template(self.template)
            logger.info('Using default template: {0}.'.format(self.template))

        ret = jinja_template.render(data=data, name_convertor=name_convertor)
        return re.sub(r'[ \t]+\n', "\n", ret) 
Example #30
Source File: loader.py    From rally with Apache License 2.0 4 votes vote down vote up
def render_template(template_source, template_vars=None, template_internal_vars=None, loader=None):
    macros = [
        """
        {% macro collect(parts) -%}
            {% set comma = joiner() %}
            {% for part in glob(parts) %}
                {{ comma() }}
                {% include part %}
            {% endfor %}
        {%- endmacro %}
        """,
        """
        {% macro exists_set_param(setting_name, value, default_value=None, comma=True) -%}
            {% if value is defined or default_value is not none %}
                {% if comma %} , {% endif %}
                {% if default_value is not none %}
                  "{{ setting_name }}": {{ value | default(default_value) | tojson }}
                {% else %}
                  "{{ setting_name }}": {{ value | tojson }}
                {% endif %}
              {% endif %}
        {%- endmacro %}
        """
    ]

    # place helpers dict loader first to prevent users from overriding our macros.
    env = jinja2.Environment(
        loader=jinja2.ChoiceLoader([
            jinja2.DictLoader({"rally.helpers": "".join(macros)}),
            jinja2.BaseLoader(),
            loader
        ])
    )

    if template_vars:
        for k, v in template_vars.items():
            env.globals[k] = v
    # ensure that user variables never override our internal variables
    if template_internal_vars:
        for macro_type in template_internal_vars:
            for env_global_key, env_global_value in template_internal_vars[macro_type].items():
                getattr(env, macro_type)[env_global_key] = env_global_value

    template = env.from_string(template_source)
    return template.render()