예제 #1
0
def get_jinja_env(force_filesystemloader=False):
    if tba_config.CONFIG[
            'use-compiled-templates'] and not force_filesystemloader:
        logging.info("Using jinja2.ModuleLoader")
        env = jinja2.Environment(auto_reload=False,
                                 loader=jinja2.ModuleLoader(
                                     os.path.join(
                                         os.path.dirname(__file__),
                                         '../templates_jinja2_compiled.zip')),
                                 extensions=['jinja2.ext.autoescape'],
                                 autoescape=True)
    else:
        logging.info("Using jinja2.FileSystemLoader")
        env = jinja2.Environment(loader=jinja2.FileSystemLoader(
            os.path.join(os.path.dirname(__file__), '../templates_jinja2')),
                                 extensions=['jinja2.ext.autoescape'],
                                 autoescape=True)
    env.filters['digits'] = jinja2_filters.digits
    env.filters['floatformat'] = jinja2_filters.floatformat
    env.filters['strftime'] = jinja2_filters.strftime
    env.filters['strip_frc'] = jinja2_filters.strip_frc
    env.filters['urlencode'] = jinja2_filters.urlencode
    env.filters['rfc2822'] = jinja2_filters.rfc2822
    # env.filters['slugify'] = jinja2_filters.slugify
    return env
예제 #2
0
def get_jinja_env(force_filesystemloader=False):
    if tba_config.CONFIG['use-compiled-templates'] and not force_filesystemloader:
        logging.info("Using jinja2.ModuleLoader")
        env = jinja2.Environment(
            auto_reload=False,
            loader=jinja2.ModuleLoader(os.path.join(os.path.dirname(__file__), '../templates_jinja2_compiled.zip')),
            extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'],
            autoescape=True)
    else:
        logging.info("Using jinja2.FileSystemLoader")
        env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), '../templates_jinja2')),
            extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'],
            autoescape=True)
    env.filters['ceil'] = jinja2_filters.ceil
    env.filters['defense_name'] = jinja2_filters.defense_name
    env.filters['digits'] = jinja2_filters.digits
    env.filters['floatformat'] = jinja2_filters.floatformat
    env.filters['isoformat'] = jinja2_filters.isoformat
    env.filters['limit_prob'] = jinja2_filters.limit_prob
    env.filters['union'] = jinja2_filters.union
    env.filters['strftime'] = jinja2_filters.strftime
    env.filters['strip_frc'] = jinja2_filters.strip_frc
    env.filters['urlencode'] = jinja2_filters.urlencode
    env.filters['rfc2822'] = jinja2_filters.rfc2822
    env.filters['slugify'] = jinja2_filters.slugify
    env.filters['yt_start'] = jinja2_filters.yt_start
    env.filters['match_short'] = jinja2_filters.match_short
    return env
예제 #3
0
    def __init__(self, templates, cache, cache_dir):

        # PERF: This function is simply constructing a Jinja environment and
        # would be trivial, except that we optimise re-execution of template
        # code by compiling the templates to Python bytecode the first time
        # they are seen. This happens when the compilation cache is enabled and
        # should speed the execution of the template code itself in future
        # runs.

        self.templates = templates

        # Directory in which to store and fetch pre-compiled Jinja2 templates.
        template_cache = os.path.join(cache_dir, version(),
                                      'precompiled-templates')

        loaders = []
        if cache and os.path.exists(template_cache):
            # Pre-compiled templates.
            loaders.append(jinja2.ModuleLoader(template_cache))

        # Source templates.
        loaders.extend(
            jinja2.FileSystemLoader(os.path.abspath(x))
            for x in templates.get_roots())

        self.env = jinja2.Environment(
            loader=jinja2.ChoiceLoader(loaders),
            extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
            block_start_string=START_BLOCK,
            block_end_string=END_BLOCK,
            variable_start_string=START_VARIABLE,
            variable_end_string=END_VARIABLE,
            comment_start_string=START_COMMENT,
            comment_end_string=END_COMMENT,
            auto_reload=False,
            undefined=jinja2.StrictUndefined)

        if cache and not os.path.exists(template_cache):
            # The pre-compiled template cache is enabled but does not exist.
            # We build it here for next time.

            # We filter the templates that Jinja compiles to only the ones we
            # know of in order to avoid errors or wasted time on other stray
            # garbage in the template directory (vim swp files, pycs, ...).
            templates = list(get_leaves(TEMPLATES))

            mkdirp(template_cache)

            # Compile the templates. Note that we only compile them to PYCs on
            # Python 2, because this has no effect on Python 3 or PyPy.
            self.env.compile_templates(
                template_cache,
                filter_func=(lambda x: x in templates),
                zip=None,
                ignore_errors=False,
                py_compile=platform.python_implementation() == 'CPython'
                and six.PY2)
예제 #4
0
    def __init__(self, app, config=None):
        """Initializes the Jinja2 object.

        :param app:
            A :class:`webapp2.WSGIApplication` instance.
        :param config:
            A dictionary of configuration values to be overridden. See
            the available keys in :data:`default_config`.
        """
        self.config = config = app.config.load_config(
            self.config_key,
            default_values=default_config,
            user_values=config,
            required_keys=None
        )
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if 'loader' not in kwargs:
            template_path = config['template_path']
            compiled_path = config['compiled_path']
            use_compiled = not app.debug or config['force_compiled']

            if compiled_path and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = jinja2.ModuleLoader(compiled_path)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = jinja2.FileSystemLoader(template_path)

        # Initialize the environment.
        env = jinja2.Environment(**kwargs)

        if config['globals']:
            env.globals.update(config['globals'])

        if config['filters']:
            env.filters.update(config['filters'])

        if enable_i18n:
            # Install i18n.
            from webapp2_extras import i18n
            env.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True)
            env.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })

        self.environment = env
예제 #5
0
 def getTemplateEnv(template_dir: str = '/templates',
                    additional_loader=None):
     loader = []
     if additional_loader is not None:
         loader.append(
             jinja2.FileSystemLoader(searchpath=additional_loader))
     script_dir = os.path.dirname(wikifile.__file__) + "/.."
     loader.append(jinja2.FileSystemLoader(script_dir + template_dir))
     loader.append(jinja2.ModuleLoader(get_python_lib() + template_dir))
     templateLoader = jinja2.ChoiceLoader(loader)
     templateEnv = jinja2.Environment(loader=templateLoader)
     return WikiRender.extend_template_env(templateEnv)
예제 #6
0
def ApplyTemplate(mojo_generator, path_to_template, params, **kwargs):
    loader = jinja2.ModuleLoader(
        os.path.join(mojo_generator.bytecode_path,
                     "%s.zip" % mojo_generator.GetTemplatePrefix()))
    final_kwargs = dict(mojo_generator.GetJinjaParameters())
    final_kwargs.update(kwargs)
    jinja_env = jinja2.Environment(loader=loader,
                                   keep_trailing_newline=True,
                                   **final_kwargs)
    jinja_env.globals.update(mojo_generator.GetGlobals())
    jinja_env.filters.update(mojo_generator.GetFilters())
    template = jinja_env.get_template(path_to_template)
    return template.render(params)
예제 #7
0
    def __init__(self, template_paths, options):

        # PERF: This function is simply constructing a Jinja environment and
        # would be trivial, except that we optimise re-execution of template
        # code by compiling the templates to Python bytecode the first time
        # they are seen. This happens when the compilation cache is enabled and
        # should speed the execution of the template code itself in future
        # runs.

        # Directory in which to store and fetch pre-compiled Jinja2 templates.
        template_cache = os.path.join(options.cache_dir, version_hash(),
                                      'precompiled-templates')

        loaders = []
        if options.cache in ['on', 'readonly'] and \
                os.path.exists(template_cache):
            # Pre-compiled templates.
            loaders.append(jinja2.ModuleLoader(template_cache))

        # Source templates.
        loaders.extend(
            map(jinja2.FileSystemLoader,
                [os.path.abspath(x) for x in template_paths]))

        self.env = jinja2.Environment(
            loader=jinja2.ChoiceLoader(loaders),
            extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
            block_start_string=START_BLOCK,
            block_end_string=END_BLOCK,
            variable_start_string=START_VARIABLE,
            variable_end_string=END_VARIABLE,
            comment_start_string=START_COMMENT,
            comment_end_string=END_COMMENT,
            auto_reload=False)

        if options.cache in ['on', 'writeonly'] and \
                not os.path.exists(template_cache):
            # The pre-compiled template cache is enabled but does not exist.
            # We build it here for next time.

            # We filter the templates that Jinja compiles to only the ones we
            # know of in order to avoid errors or wasted time on other stray
            # garbage in the template directory (vim swp files, pycs, ...).
            templates = list(get_leaves(TEMPLATES))

            mkdirp(template_cache)
            self.env.compile_templates(template_cache,
                                       filter_func=(lambda x: x in templates),
                                       zip=None,
                                       ignore_errors=False,
                                       py_compile=True)
예제 #8
0
    def __init__(self, app):
        config = app.config[__name__]
        kwargs = config['environment_args'].copy()
        enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', [])

        if 'loader' not in kwargs:
            template_path = config['template_path']
            compiled_path = config['compiled_path']
            use_compiled = not app.debug or config['force_compiled']

            if compiled_path and use_compiled:
                # Use precompiled templates loaded from a module or zip.
                kwargs['loader'] = jinja2.ModuleLoader(compiled_path)
            else:
                # Parse templates for every new environment instances.
                kwargs['loader'] = jinja2.FileSystemLoader(template_path)

        # Initialize the environment.
        env = jinja2.Environment(**kwargs)

        if config['globals']:
            env.globals.update(config['globals'])

        if config['filters']:
            env.filters.update(config['filters'])

        if enable_i18n:
            # Install i18n.
            from webapp2_extras import i18n
            env.install_gettext_callables(
                lambda x: i18n.gettext(x),
                lambda s, p, n: i18n.ngettext(s, p, n),
                newstyle=True)
            env.filters.update({
                'format_date':      i18n.format_date,
                'format_time':      i18n.format_time,
                'format_datetime':  i18n.format_datetime,
                'format_timedelta': i18n.format_timedelta,
            })

        self.environment = env
예제 #9
0
import sys

# Load up our app and all its dependencies. Make the environment sane.
sys.path.insert(0, './lib/')
from dpxdt.server import app

# For debugging SQL queries.
# import logging
# logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG)

# When in production use precompiled templates. Sometimes templates break
# in production. To debug templates there, comment this out entirely.
if os.environ.get('SERVER_SOFTWARE', '').startswith('Google App Engine'):
    import jinja2
    app.jinja_env.auto_reload = False
    app.jinja_env.loader = jinja2.ModuleLoader('templates_compiled.zip')

# Install dpxdt.server override hooks.
from dpxdt.server import api
import hooks

api._artifact_created = hooks._artifact_created
api._get_artifact_response = hooks._get_artifact_response

# Don't log when appstats is active.
appstats_DUMP_LEVEL = -1

# SQLAlchemy stacks are really deep.
appstats_MAX_STACK = 20

# Use very shallow local variable reprs to reduce noise.