Example #1
0
    def setup(self, app):
        self.app = app

        TEMPLATE_PATH[:] = [self.template_path]

        Jinja2Template.settings = {
            'autoescape':
            True,
            'filters': {
                'datetimeformat': datetimeformat,
                'time_passed': time_passed,
                'ternary': ternary
            },
            'bytecode_cache':
            FileSystemBytecodeCache(app.config['site.jinja2_cache'],
                                    '%s.cache')
        }

        Jinja2Template.defaults = {
            'request': request,
            'view_name': view_name,
            'url_for': url_for,
            'view_func': view_func,
            'config': app.config,
            'debug': DEBUG
        }
Example #2
0
async def web_server(port, host='0.0.0.0', ssl_context=None):
    """http web server"""
    try:
        app = web.Application(middlewares=[error_middleware])
        web_root_dir = os.path.split(os.path.abspath(__file__))[0]
        cache_path = os.path.join(web_root_dir, '.cache')
        static_path = os.path.join(web_root_dir, 'templates', 'static')
        if not os.path.exists(cache_path):
            os.mkdir(cache_path)
        aiohttp_jinja2.setup(
            app=app,
            loader=FileSystemLoader(os.path.join(web_root_dir, 'templates')),
            bytecode_cache=FileSystemBytecodeCache(directory=cache_path, pattern='%s.cache'),
            extensions=['jinja2_time.TimeExtension'],
        )
        # add routes
        app.router.add_get('/', page_index)
        app.router.add_get('/index.html', page_index)
        app.router.add_get('/started.html', page_started)
        app.router.add_get('/dashboard.html', page_dashboard)
        app.router.add_get('/explorer.html', page_explorer)
        app.router.add_get('/connection.html', page_connection)
        app.router.add_get('/status.html', page_status)
        app.router.add_get('/terms.html', page_terms)
        app.router.add_static('/static', static_path)
        # start server
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, host=host, port=port, ssl_context=ssl_context)
        await site.start()
        log.info(f"start web server {host}:{port} ssl={bool(ssl_context)}")
    except Exception:
        log.error("web server exception", exc_info=True)
 def initialize(cls):
     cls._environment = Environment(
         undefined=StrictUndefined,
         autoescape=select_autoescape(enabled_extensions=()),
         loader=FileSystemLoader(TEMPLATES_DIRECTORY_PATH),
         bytecode_cache=FileSystemBytecodeCache(
             directory=TEMPLATES_BYTECODE_CACHE_DIRECTORY_PATH))
Example #4
0
 def __init__(self, templates_dir):
     self.templates_dir = templates_dir
     self.jinja2_env = Environment(
         loader=FileSystemLoader(self.templates_dir),
         bytecode_cache=FileSystemBytecodeCache(self.templates_dir),
         auto_reload=False,
         optimized=True,
         autoescape=select_autoescape(['htm', 'html', 'xml', 'json']))
 def __init__(self, template_path, extensions=()):
     self.template_path = template_path
     self._loader = FileSystemLoader(template_path)
     self._bytecode_cache = FileSystemBytecodeCache()
     self._environment = Environment(loader=self._loader,
                                     cache_size=-1,
                                     line_statement_prefix='##',
                                     extensions=extensions,
                                     autoescape=True,
                                     bytecode_cache=self._bytecode_cache)
Example #6
0
def get_jinja_env_options():
    return dict(loader=CkanFileSystemLoader(config['computed_template_paths']),
                autoescape=True,
                extensions=[
                    'jinja2.ext.do', 'jinja2.ext.with_', SnippetExtension,
                    CkanExtend, CkanInternationalizationExtension,
                    LinkForExtension, ResourceExtension, UrlForStaticExtension,
                    UrlForExtension
                ],
                bytecode_cache=FileSystemBytecodeCache())
Example #7
0
def _get_or_build_default_environment(registry):
    environment = registry.queryUtility(IJinja2Environment)
    if environment is not None:
        return environment

    settings = registry.settings
    kw = {}
    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    reload_templates = asbool(settings.get('reload_templates', False))
    autoescape = asbool(settings.get('jinja2.autoescape', True))
    domain = settings.get('jinja2.i18n.domain', 'messages')
    debug = asbool(settings.get('debug_templates', False))
    input_encoding = settings.get('jinja2.input_encoding', 'utf-8')

    extensions = parse_multiline(settings.get('jinja2.extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')

    undefined = parse_undefined(settings.get('jinja2.undefined', ''))

    directories = parse_multiline(settings.get('jinja2.directories') or '')
    directories = [abspath_from_resource_spec(d, package) for d in directories]
    loader = SmartAssetSpecLoader(directories,
                                  encoding=input_encoding,
                                  debug=debug)

    # bytecode caching
    bytecode_caching = asbool(settings.get('jinja2.bytecode_caching', True))
    bytecode_caching_directory = settings.get(
        'jinja2.bytecode_caching_directory', None)
    if bytecode_caching:
        kw['bytecode_cache'] = FileSystemBytecodeCache(
            bytecode_caching_directory)

    environment = Environment(loader=loader,
                              auto_reload=reload_templates,
                              autoescape=autoescape,
                              extensions=extensions,
                              undefined=undefined,
                              **kw)

    # register pyramid i18n functions
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext, wrapper.ngettext)

    # register global repository for templates
    if package is not None:
        environment._default_package = package.__name__

    filters = parse_filters(settings.get('jinja2.filters', ''))
    environment.filters.update(filters)

    registry.registerUtility(environment, IJinja2Environment)
    return registry.queryUtility(IJinja2Environment)
Example #8
0
def environment(**options: Any) -> Environment:
    cache_path = Path("./cache/")
    cache_path.mkdir(exist_ok=True)
    fsbc = FileSystemBytecodeCache(cache_path)
    options["trim_blocks"] = True
    options["lstrip_blocks"] = True
    options["bytecode_cache"] = fsbc
    env = Environment(**options)
    env.globals.update({"static": static, "url": reverse, "DEBUG": settings.DEBUG, "page_url": page_url, "is_current": is_current})
    env.globals.update(settings.TEMPLATE_ENVS)
    return env
Example #9
0
 def __init__(self, conf: appconf.Conf, assets_url: str):
     self._dir_metadata = {}
     self._cache = FileSystemBytecodeCache(
         conf.template_cache_dir) if conf.template_cache_dir else None
     self._assets_url = assets_url
     self._template_env: Environment = Environment(
         loader=FileSystemLoader(
             os.path.realpath(
                 os.path.join(os.path.dirname(__file__), 'templates'))),
         bytecode_cache=self._cache,
         trim_blocks=True,
         lstrip_blocks=True)
Example #10
0
 def __init__(self, root_directory, cache_path=None, cache_size=-1,
              auto_reload=False,
              autoescape=True, **kwargs):
     super(Jinja2Loader, self).__init__(root_directory, **kwargs)
     bcc = None
     if cache_path:
         # if not os.path.exists(cache_path):
         #     os.makedirs(cache_path)
         bcc = FileSystemBytecodeCache(directory=cache_path)
     self.env = Environment(loader=FileSystemLoader(self.root), bytecode_cache=bcc,
                            auto_reload=auto_reload,
                            cache_size=cache_size,
                            autoescape=autoescape)
Example #11
0
    def __init__(self):
        loaders = {}
        for resource in ctx.get_implementations(IResourceManager, instances=True):
            loaders[resource.resource_name] = FileSystemLoader(resource.templates_path)

        loader = ChoiceLoader([FileSystemLoader(ctx.cfg['templates.path']),
                               PrefixLoader(loaders)])

        cache_obj = None
        if ctx.cfg['templates.use_cache']:
            if ctx.cfg['templates.use_memcached_cache']:
                cache_obj = MemcachedBytecodeCache(
                    client=inyoka_cache,
                    timeout=ctx.cfg['caching.timeout']
                )
            elif ctx.cfg['templates.use_filesystem_cache']:
                cache_obj = FileSystemBytecodeCache(
                    directory=ctx.cfg['caching.filesystem_cache_path'],
                )

        Environment.__init__(self,
            loader=loader,
            extensions=['jinja2.ext.i18n', 'jinja2.ext.do', 'jinja2.ext.with_',
                        'jinja2.ext.autoescape'],
            auto_reload=ctx.cfg['templates.auto_reload'],
            undefined=StrictUndefined,
            cache_size=-1,
            bytecode_cache=cache_obj,
            autoescape=True
        )

        self.globals.update(
            INYOKA_REVISION=INYOKA_REVISION,
            PYTHON_VERSION='%d.%d.%d' % sys.version_info[:3],
            DEBUG=ctx.cfg['debug'],
            href=href,
        )
        self.filters.update(
            jsonencode=json.dumps,
            datetimeformat=l10n.format_datetime,
            dateformat=l10n.format_date,
            timeformat=l10n.format_time,
            timedelta=l10n.timedeltaformat,
            monthformat=l10n.format_month,
            dayformatshort=l10n.format_day_short,
            humanize=l10n.humanize_number,
        )
        self.install_gettext_translations(
            i18n.get_translations(),
            newstyle=True
        )
 def __init__(self, templatefile):
     self._has_newline = False
     self.templateFile = templatefile
     if not os.path.isdir(CACHE_DIR):
         os.mkdir(CACHE_DIR)
     cache = FileSystemBytecodeCache(CACHE_DIR, "%s.cache")
     templateName = os.path.basename(templatefile)
     loader = FileSystemLoader(os.path.dirname(templatefile))
     self.env = Environment(trim_blocks=True,
                            lstrip_blocks=True,
                            loader=loader,
                            bytecode_cache=cache,
                            keep_trailing_newline=True)
     self.template = self.env.get_template(templateName)
Example #13
0
    def JINJA_ENV(self):
        from engineer.filters import format_datetime, markdown_filter, localtime, naturaltime, compress
        from engineer.processors import preprocess_less
        from engineer.themes import ThemeManager

        # Configure Jinja2 environment
        logger.debug("Configuring the Jinja environment.")

        # Helper function to look up a URL by name
        def urlname(name, *args):
            url = settings.URLS.get(name, settings.HOME_URL)
            if isfunction(url):
                return url(*args)
            else:
                return url

        env = Environment(
            loader=ChoiceLoader([
                FileSystemLoader([self.TEMPLATE_DIR]),
                ThemeManager.current_theme().template_loader,
                #self.ENGINEER.THEMES_DIR / 'base_templates',
                FileSystemLoader([self.ENGINEER.TEMPLATE_DIR])
            ]),
            extensions=[
                'jinja2.ext.with_',
            ],
            #'compressinja.html.HtmlCompressor'],
            bytecode_cache=FileSystemBytecodeCache(
                directory=self.JINJA_CACHE_DIR),
            trim_blocks=True)

        # Filters
        env.filters['compress'] = compress
        env.filters['date'] = format_datetime
        env.filters['localtime'] = localtime
        env.filters['naturaltime'] = naturaltime
        env.filters['markdown'] = markdown_filter
        env.filters['typogrify_no_widont'] = typogrify_no_widont
        register(env)  # register typogrify filters

        # Globals
        env.globals['theme'] = ThemeManager.current_theme()
        env.globals['urlname'] = urlname
        env.globals['preprocess_less'] = preprocess_less
        #        env.globals['url'] = url
        env.globals['STATIC_URL'] = self.STATIC_URL
        env.globals['DEBUG'] = self.DEBUG
        env.globals['settings'] = self
        return env
Example #14
0
 def _setup_bytecode_cache(self):
     cache_type = config.get('jinja_bytecode_cache_type')
     bcc = None
     try:
         if cache_type == 'memcached' and config.get('memcached_host'):
             import pylibmc
             from jinja2 import MemcachedBytecodeCache
             client = pylibmc.Client([config['memcached_host']])
             bcc = MemcachedBytecodeCache(client)
         elif cache_type == 'filesystem':
             from jinja2 import FileSystemBytecodeCache
             bcc = FileSystemBytecodeCache()
     except:
         log.exception("Error encountered while setting up a" +
                       " %s-backed bytecode cache for Jinja" % cache_type)
     return bcc
Example #15
0
def environment(**options):
    '''
  Setup Jinja2 environment:
  '''
    # Init environment
    env = Environment(**options)

    # Use template with some common context
    env.template_class = ContextTemplate

    # Add our custom filters
    env.filters.update({
        'addcss': addcss,
        'total_time': total_time,
        'convert_speed': convert_speed,
        'convert_speed_kmh': convert_speed_kmh,
        'total_distance': total_distance,
    })

    # Add constants from settings
    keys = [
        'DEBUG',
        'PIWIK_HOST',
        'PIWIK_ID',
        'FACEBOOK_ID',
        'LANGUAGES',
        'PAYMILL_PUBLIC',
        'HELP_URL',
        'PAYMENTS_ENABLED',
        'VERSION',
    ]
    env.globals.update(dict([(k, getattr(settings, k, None)) for k in keys]))

    # Setup translations
    translation = import_module('django.utils.translation')
    env.install_gettext_translations(translation, newstyle=False)

    # In Prod, skip auto_reload
    # and setup bytecode cache
    if not settings.DEBUG:
        env.auto_reload = False
        cache_dir = os.path.join(settings.HOME, 'templates_cached')
        if not os.path.exists(cache_dir):
            os.mkdir(cache_dir)
        env.bytecode_cache = FileSystemBytecodeCache(cache_dir, 'rr.%s.cache')

    return env
Example #16
0
    def init(self, layoutdir, cachedir):
        self.jinja2 = J2Environemnt(
            loader=ExtendedFileSystemLoader(layoutdir),
            bytecode_cache=FileSystemBytecodeCache(cachedir))

        # jinja2 is stupid and can't import any module during runtime
        import time, datetime, urllib

        for module in (time, datetime, urllib):
            self.jinja2.globals[module.__name__] = module

            for name in dir(module):
                if name.startswith('_'):
                    continue
                if callable(getattr(module, name)):
                    self.jinja2.filters[module.__name__ + '.' +
                                        name] = getattr(module, name)
Example #17
0
    def reset_environment(self, cls: Type[Environment] = Environment):
        """Reset the Jinja environment."""
        self.env = cls(
            autoescape=False,
            line_statement_prefix="#!",
            keep_trailing_newline=True,
            loader=ChoiceLoader(self.loaders),
            bytecode_cache=FileSystemBytecodeCache(str(self.cache_dir)),
            extensions=[
                DebugExtension,
                ExprStmtExtension,
                LoopControlExtension,
            ],
        )

        setattr(self.env, "_beet_template_manager", self)
        self.env.context_class = FallbackContext
Example #18
0
def view(tpl_path):
    if not tpl_path:
        return None

    jinja2_env = Environment(
        loader=FileSystemLoader(tpl_path),
        bytecode_cache=FileSystemBytecodeCache(tpl_path),
        auto_reload=False,
        optimized=True,
        autoescape=select_autoescape(['htm', 'html', 'xml', 'json']))

    def render(tpl_file, variable):
        engine = jinja2_env.get_template(tpl_file)
        result = engine.render(variable)
        return str(result)

    return render
Example #19
0
 def _setup_bytecode_cache(cls):
     cache_type = config.get('jinja_bytecode_cache_type')
     bcc = None
     try:
         if cache_type == 'memcached' and config.get('memcached_host'):
             import pylibmc
             from jinja2 import MemcachedBytecodeCache
             client = pylibmc.Client([config['memcached_host']])
             bcc_prefix = 'jinja2/{}/'.format(jinja2.__version__)
             if six.PY3:
                 bcc_prefix += 'py{}{}/'.format(sys.version_info.major, sys.version_info.minor)
             bcc = MemcachedBytecodeCache(client, prefix=bcc_prefix)
         elif cache_type == 'filesystem':
             from jinja2 import FileSystemBytecodeCache
             bcc = FileSystemBytecodeCache(pattern='__jinja2_{}_%s.cache'.format(jinja2.__version__))
     except Exception:
         log.exception("Error encountered while setting up a" +
                       " %s-backed bytecode cache for Jinja" % cache_type)
     return bcc
Example #20
0
 def run(self):
     logger.debug("screen_out_score_plot.py, ScorePlot, run()")
     if not os.path.exists("./cache"):
         os.mkdir("./cache")
     env = Environment(loader=FileSystemLoader('./templates',
                                               encoding='utf8'),
                       bytecode_cache=FileSystemBytecodeCache(
                           directory="./cache", pattern="%s.cache"))
     tpl = env.get_template('index.html')
     data = {
         "protain_names": self.name,
         "acc": self.acc,
         "score": self.score,
         "seq": self.sequence,
         "threshold": config.threshold_val,
         "percentage": self.succeed_score_rate,
     }
     html = tpl.render(data=data)
     with open("./index.html", "w") as f:
         print(str(html), file=f)
     webbrowser.open_new_tab(os.path.abspath("./index.html"))
Example #21
0
    def email(self, mail_list, rd_list, wdata, module_name):
        status, output = commands.getstatusoutput('date -d-1day "+%Y%m%d"')
        filename = "../data/%s_%s" % (module_name, output)
        (key_target, detail) = self.data2template(wdata)
        f = codecs.open(filename, 'w', "gbk")

        from jinja2 import Environment, FileSystemLoader, FileSystemBytecodeCache
        env = Environment(loader=FileSystemLoader('../template/'),
                          bytecode_cache=FileSystemBytecodeCache(
                              '../template/', '%s.cache'))
        tmpl_jinja = env.get_template('testjinja2.html')
        template = tmpl_jinja.render(key_target=key_target, detail=detail)
        print >> f, template
        f.close()
        (status, output) = commands.getstatusoutput(
            'cat %s |formail -I "From: [email protected]" -I "To:%s"  -I "MIME-Version:1.0" -I "Content-type:text/html;charset=gb2312" -I "Subject:%s"|/usr/sbin/sendmail  -oi %s'
            % (filename, mail_list, os.path.basename(
                self.parameter[2]), mail_list))
        #(status, output) = commands.getstatusoutput('cat %s | mail -s "%s" %s'%(filename,os.path.basename(self.parameter[2]),mail_list))
        print output
        return status
Example #22
0
    def __init__(self, layoutdir, cachedir):

        self.templates = {}
        self.loader = ExtendedFileSystemLoader(layoutdir)

        self._jinja2 = J2Environemnt(
            loader=self.loader,
            bytecode_cache=FileSystemBytecodeCache(cachedir))

        # jinja2 is stupid and can't import any module during runtime
        import time, datetime, urllib

        for module in (time, datetime, urllib):
            self._jinja2.globals[module.__name__] = module

            for name in dir(module):
                if name.startswith('_'):
                    continue
                obj = getattr(module, name)
                if hasattr(obj, '__class__') and callable(obj):
                    self._jinja2.filters[module.__name__ + '.' + name] = obj
Example #23
0
    def __init__(self, templates: List[FileSystemPath],
                 cache_dir: FileSystemPath):
        self.prefix_map = {}
        self.directories = templates

        self.loaders = [
            FileSystemLoader(self.directories),
            PrefixLoader(self.prefix_map),
        ]

        self.env = Environment(
            autoescape=False,
            line_statement_prefix="#!",
            keep_trailing_newline=True,
            loader=ChoiceLoader(self.loaders),
            bytecode_cache=FileSystemBytecodeCache(cache_dir),
            extensions=[
                DebugExtension,
                ExprStmtExtension,
                LoopControlExtension,
                WithExtension,
                DedentExtension,
            ],
        )
Example #24
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# @author   [email protected]
# @date     2016-1-9
#
import os
from jinja2 import Environment, FileSystemLoader, FileSystemBytecodeCache
from tornado.template import Loader
from tornadopy.settings_manager import settings
from jinja2.defaults import *
from jinja2.runtime import Undefined

_CACHE = FileSystemBytecodeCache()
_LOADER = FileSystemLoader([])
cfg = settings.TEMPLATE_CONFIG
_JINJA_ENV = Environment(bytecode_cache=_CACHE,
                         autoescape=cfg.get('autoescape', False),
                         cache_size=cfg.get('cache_size', 50),
                         auto_reload=cfg.get('filesystem_checks', True),
                         loader=_LOADER,
                         block_start_string=cfg.get('block_start_string',
                                                    BLOCK_START_STRING),
                         block_end_string=cfg.get('block_end_string',
                                                  BLOCK_END_STRING),
                         variable_start_string=cfg.get('variable_start_string',
                                                       VARIABLE_START_STRING),
                         variable_end_string=cfg.get('variable_end_string',
                                                     VARIABLE_END_STRING),
                         comment_start_string=cfg.get('comment_start_string',
Example #25
0
from settings import URL

# from django.template import RequestContext

loader_array = []
for pth in getattr(settings, 'TEMPLATE_DIRS', ()):
    loader_array.append(FileSystemLoader(pth))

for app in settings.INSTALLED_APPS:
    loader_array.append(PackageLoader(app))

default_mimetype = getattr(settings, 'DEFAULT_CONTENT_TYPE')
global_exts = getattr(settings, 'JINJA_EXTS', ())

bcc = FileSystemBytecodeCache(settings.DIR_ROOT + '/tmp', 'sorema_%s.cache')
env = Environment(extensions=global_exts,
                  loader=ChoiceLoader(loader_array),
                  bytecode_cache=bcc)

global_imports = getattr(settings, 'JINJA_GLOBALS', ())
for imp in global_imports:
    method = get_callable(imp)
    method_name = getattr(method, 'jinja_name', None)
    if not method_name == None:
        env.globals[method_name] = method
    else:
        env.globals[method.__name__] = method

global_filters = getattr(settings, 'JINJA_FILTERS', ())
for imp in global_filters:
Example #26
0
from typing import Optional, Tuple

from jinja2 import Environment, FileSystemLoader, FileSystemBytecodeCache
from .errors import UnknownTypeError, TooBigEntityError
from .config import conf
from .ext.const import work_directory, ws_magic_string

template_path = conf.get("template", "template_path")
cache_path = conf.get("template", "cache_path")

loader = FileSystemLoader(template_path)

if conf.get("template", "use_fs_cache"):
    if not os.path.exists(cache_path):
        os.mkdir(cache_path)
    bc_cache = FileSystemBytecodeCache(
        os.path.join(work_directory, cache_path), "%s.cache")
else:
    bc_cache = None
env = Environment(loader=loader,
                  bytecode_cache=bc_cache,
                  enable_async=False,
                  autoescape=True)


# "--" + self.bound + "\r\n" + http_like_data + "\r\n"
class PostDataManager:
    def __init__(self,
                 request,
                 reader: asyncio.StreamReader,
                 buf_size=16384,
                 limit=10485760):  # 10M
Example #27
0
    def configure(self, site, engine=None):
        """
        Uses the site object to initialize the jinja environment.
        """
        self.site = site
        self.engine = engine
        self.preprocessor = (engine.preprocessor if hasattr(
            engine, 'preprocessor') else None)

        self.loader = HydeLoader(self.sitepath, site, self.preprocessor)

        default_extensions = [
            IncludeText, Spaceless, Asciidoc, Markdown, restructuredText,
            Syntax, Reference, Refer, YamlVar, 'jinja2.ext.do',
            'jinja2.ext.loopcontrols', 'jinja2.ext.with_'
        ]

        defaults = {
            'line_statement_prefix': '$$$',
            'trim_blocks': True,
        }

        settings = dict()
        settings.update(defaults)
        settings['extensions'] = list()
        settings['extensions'].extend(default_extensions)

        conf = {}

        try:
            conf = attrgetter('config.jinja2')(site).to_dict()
        except AttributeError:
            pass

        settings.update(
            dict([(key, conf[key]) for key in defaults if key in conf]))

        extensions = conf.get('extensions', [])
        if isinstance(extensions, list):
            settings['extensions'].extend(extensions)
        else:
            settings['extensions'].append(extensions)

        self.env = Environment(
            loader=self.loader,
            undefined=SilentUndefined,
            line_statement_prefix=settings['line_statement_prefix'],
            trim_blocks=True,
            bytecode_cache=FileSystemBytecodeCache(),
            extensions=settings['extensions'])
        self.env.globals['media_url'] = media_url
        self.env.globals['content_url'] = content_url
        self.env.globals['full_url'] = full_url
        self.env.globals['engine'] = engine
        self.env.globals['deps'] = {}
        self.env.filters['urlencode'] = urlencode
        self.env.filters['urldecode'] = urldecode
        self.env.filters['asciidoc'] = asciidoc
        self.env.filters['markdown'] = markdown
        self.env.filters['restructuredtext'] = restructuredtext
        self.env.filters['syntax'] = syntax
        self.env.filters['date_format'] = date_format
        self.env.filters['xmldatetime'] = xmldatetime
        self.env.filters['islice'] = islice
        self.env.filters['top'] = top

        config = {}
        if hasattr(site, 'config'):
            config = site.config

        self.env.extend(config=config)

        try:
            from typogrify.templatetags import jinja2_filters
        except ImportError:
            jinja2_filters = False

        if jinja2_filters:
            jinja2_filters.register(self.env)
Example #28
0
def parse_env_options_from_settings(
    settings,
    prefix,
    maybe_dotted,
    package,
    defaults=None,
):
    """ Parse options for use with the Jinja2 Environment."""
    def sget(name, default=None):
        return settings.get(prefix + name, default)

    if defaults is None:
        defaults = _JINJA2_ENVIRONMENT_DEFAULTS

    opts = {}

    reload_templates = sget('reload_templates')
    if reload_templates is None:
        reload_templates = settings.get('pyramid.reload_templates')
    opts['auto_reload'] = asbool(reload_templates)

    # set string settings
    for key_name in ('block_start_string', 'block_end_string',
                     'variable_start_string', 'variable_end_string',
                     'comment_start_string', 'comment_end_string',
                     'line_statement_prefix', 'line_comment_prefix',
                     'newline_sequence'):
        value = sget(key_name, defaults.get(key_name))
        if value is not None:
            opts[key_name] = value

    # boolean settings
    for key_name in ('autoescape', 'trim_blocks', 'optimized'):
        value = sget(key_name, defaults.get(key_name))
        if value is not None:
            opts[key_name] = asbool(value)

    # integer settings
    for key_name in ('cache_size', ):
        value = sget(key_name, defaults.get(key_name))
        if value is not None:
            opts[key_name] = int(value)

    opts['undefined'] = parse_undefined(sget('undefined', ''))

    # get supplementary jinja2 settings
    domain = sget('i18n.domain', package and package.__name__ or 'messages')
    gettext_wrapper = sget('i18n.gettext', GetTextWrapper)
    if not issubclass(gettext_wrapper, GetTextWrapper):
        gettext_wrapper = maybe_dotted(gettext_wrapper)
    opts['gettext'] = gettext_wrapper(domain=domain)

    # get jinja2 extensions
    extensions = parse_multiline(sget('extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')
    opts['extensions'] = extensions

    # get jinja2 bytecode caching settings and set up bytecaching
    bytecode_caching = sget('bytecode_caching', False)
    if isinstance(bytecode_caching, BytecodeCache):
        opts['bytecode_cache'] = bytecode_caching
    elif asbool(bytecode_caching):
        bytecode_caching_directory = sget('bytecode_caching_directory', None)
        opts['bytecode_cache'] = FileSystemBytecodeCache(
            bytecode_caching_directory)

    # should newstyle gettext calls be enabled?
    opts['newstyle'] = asbool(sget('newstyle', False))

    # Do we have a finalize function?
    finalize = sget('finalize')
    if finalize is not None:
        opts['finalize'] = maybe_dotted(finalize)

    # add custom jinja2 filters
    opts['filters'] = parse_named_assetspecs(sget('filters', ''), maybe_dotted)

    # add custom jinja2 tests
    opts['tests'] = parse_named_assetspecs(sget('tests', ''), maybe_dotted)

    # add custom jinja2 functions
    opts['globals'] = parse_named_assetspecs(sget('globals', ''), maybe_dotted)

    return opts
Example #29
0
PREFIX = config.get('webui', 'prefix')

if PREFIX:
    PREFIX = PREFIX.rstrip("/")
    if not PREFIX.startswith("/"):
        PREFIX = "/" + PREFIX

DEBUG = config.get("general",
                   "debug_mode") or "-d" in sys.argv or "--debug" in sys.argv
bottle.debug(DEBUG)

cache = join("tmp", "jinja_cache")
if not exists(cache):
    makedirs(cache)

bcc = FileSystemBytecodeCache(cache, '%s.cache')

loader = FileSystemLoader([THEME_DIR, join(THEME_DIR, THEME)])

env = Environment(loader=loader,
                  extensions=['jinja2.ext.i18n', 'jinja2.ext.autoescape'],
                  trim_blocks=True,
                  auto_reload=False,
                  bytecode_cache=bcc)

from filters import quotepath, path_make_relative, path_make_absolute, truncate, date

env.filters['quotepath'] = quotepath
env.filters['truncate'] = truncate
env.filters['date'] = date
env.filters['path_make_relative'] = path_make_relative
Example #30
0
def _get_or_build_default_environment(registry):
    environment = registry.queryUtility(IJinja2Environment)
    if environment is not None:
        return environment

    settings = registry.settings
    kw = {}

    package = _caller_package(('pyramid_jinja2', 'jinja2', 'pyramid.config'))
    debug = asbool(settings.get('debug_templates', False))

    # get basic environment jinja2 settings
    kw.update(_parse_config_for_settings(settings))
    reload_templates = settings.get('reload_templates', None)
    if reload_templates is None:
        # since version 1.5, both settings are supported
        reload_templates = settings.get('pyramid.reload_templates', False)
    reload_templates = asbool(reload_templates)
    undefined = parse_undefined(settings.get('jinja2.undefined', ''))

    # get supplementary junja2 settings
    input_encoding = settings.get('jinja2.input_encoding', 'utf-8')
    domain = settings.get('jinja2.i18n.domain', package and package.__name__
                          or 'messages')

    # get jinja2 extensions
    extensions = parse_multiline(settings.get('jinja2.extensions', ''))
    if 'jinja2.ext.i18n' not in extensions:
        extensions.append('jinja2.ext.i18n')

    # get jinja2 directories
    directories = parse_multiline(settings.get('jinja2.directories') or '')
    directories = [abspath_from_resource_spec(d, package) for d in directories]
    loader = SmartAssetSpecLoader(directories,
                                  encoding=input_encoding,
                                  debug=debug)

    # get jinja2 bytecode caching settings and set up bytecaching
    bytecode_caching = asbool(settings.get('jinja2.bytecode_caching', True))
    bytecode_caching_directory = \
        settings.get('jinja2.bytecode_caching_directory', None)
    if bytecode_caching:
        kw['bytecode_cache'] = \
            FileSystemBytecodeCache(bytecode_caching_directory)
        # clear cache on exit
        atexit.register(kw['bytecode_cache'].clear)

    # should newstyle gettext calls be enabled?
    newstyle = asbool(settings.get('jinja2.newstyle', False))

    environment = Environment(loader=loader,
                              auto_reload=reload_templates,
                              extensions=extensions,
                              undefined=undefined,
                              **kw)

    # register pyramid i18n functions
    wrapper = GetTextWrapper(domain=domain)
    environment.install_gettext_callables(wrapper.gettext,
                                          wrapper.ngettext,
                                          newstyle=newstyle)

    # register global repository for templates
    if package is not None:
        environment._default_package = package.__name__

    #add custom jinja2 filters
    filters = parse_config(settings.get('jinja2.filters', ''))
    environment.filters.update(filters)

    #add custom jinja2 tests
    tests = parse_config(settings.get('jinja2.tests', ''))
    environment.tests.update(tests)

    # add custom jinja2 functions
    jinja_globals = parse_config(settings.get('jinja2.globals', ''))
    environment.globals.update(jinja_globals)

    registry.registerUtility(environment, IJinja2Environment)
    return registry.queryUtility(IJinja2Environment)