def environment(**options): if not _settings.PRE_COMPILE: env = Environment(**options) else: env = Environment(loader=ModuleLoader("src/project/target.zip")) env.globals.update({"static": static, "url": reverse, "debug": settings.DEBUG}) return env
def _init_get_env() -> Environment: # This package should not run from an archive--it's too slow to decompress every time. # Thus, `__file__` is guaranteed to be defined. package_dir = os.path.dirname(os.path.dirname(__file__)) raw_templates_dir = os.path.join(package_dir, "templates") precompiled_templates_dir = os.path.join(raw_templates_dir, "compiled") env = Environment( loader=ChoiceLoader([ ModuleLoader(precompiled_templates_dir), # Don't use `PackageLoader` because it imports `pkg_resources` internally, which is a slow operation. FileSystemLoader(raw_templates_dir), ]), # Only one template to load. cache_size=1, trim_blocks=True, lstrip_blocks=True, ) # Add functions to jinja template env.filters["namespace"] = _jinja_namespacer # Short-hand for `namespace` env.filters["ns"] = _jinja_namespacer for typename, opt_type in SurfrawOption.typenames.items(): # Account for late-binding. env.tests[f"{typename}_option"] = partial( lambda x, type_: isinstance(x, type_), type_=opt_type) return env
def get_app(): app = Flask('flask_seed') app.config.from_object('default_settings') if os.getenv('FLASK_SEED_SETTINGS', None): app.config.from_envvar('FLASK_SEED_SETTINGS') app.secret_key = app.config['SECRET_KEY'] # app.g = globals.load() app.db = MongoEngine(app) app.jinja_env.add_extension('util.Markdown2Extension') app.jinja_env.filters['slugify'] = slugify app.jinja_env.filters['timesince'] = timesince app.jinja_env.filters['timeuntil'] = timeuntil app.jinja_env.filters['jsonencode'] = jsonencode app.jinja_env.globals['newrelic_head'] = newrelic_head app.jinja_env.globals['newrelic_foot'] = newrelic_foot if not app.config.get('TEMPLATE_DEBUG', True): compiled_templates = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'compiled_templates') compiled_files = path.path(compiled_templates).files() if len(compiled_files) <= 1: app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True) app.jinja_env.loader = ModuleLoader(compiled_templates) return app
def render(self, templ_path, templ_name, cached_path): templ_compiled_path = cached_path template = '' JINJA_ENVIRONMENT = Environment( loader=ModuleLoader(templ_compiled_path), autoescape=False) try: template = JINJA_ENVIRONMENT.get_template(templ_name) except exceptions.TemplateNotFound: JINJA_COMPILE_ENVIRONMENT = Environment( loader=FileSystemLoader(templ_path), autoescape=False) JINJA_COMPILE_ENVIRONMENT.compile_templates(templ_compiled_path, zip=None) template = JINJA_COMPILE_ENVIRONMENT.get_template(templ_name) template_values = { 'data': self.tableData, 'maxInfo': self._maxInfo, 'properties': self._property_names } print template.render(template_values)
def environment(**options): if not _settings.PRE_COMPILE: env = Environment(**options) # раскоментить когда меняю содержимое шаблона или создаю новый # Environment(**options).compile_templates("src/project/target.zip") else: env = Environment(loader=ModuleLoader("src/project/target.zip")) env.globals.update({"static": static, "url": reverse, "debug": settings.DEBUG}) return env
def __init__(self, app, _globals=None, filters=None): self.app = app config = app.config[__name__] kwargs = config['environment_args'].copy() enable_i18n = 'jinja2.ext.i18n' in kwargs.get('extensions', []) if not kwargs.get('loader'): templates_compiled_target = config['templates_compiled_target'] use_compiled = not app.debug or config['force_use_compiled'] if templates_compiled_target and use_compiled: # Use precompiled templates loaded from a module or zip. kwargs['loader'] = ModuleLoader(templates_compiled_target) else: # Parse templates for every new environment instances. kwargs['loader'] = FileSystemLoader(config['templates_dir']) # Initialize the environment. env = Environment(**kwargs) if _globals: env.globals.update(_globals) if filters: env.filters.update(filters) if enable_i18n: # Install i18n. from tipfy import i18n env.install_gettext_callables( lambda x: get_request().i18n.translations.ugettext(x), lambda s, p, n: get_request().i18n.translations.ungettext( s, p, n), newstyle=True) format_functions = { 'format_date': i18n.format_date, 'format_time': i18n.format_time, 'format_datetime': i18n.format_datetime, 'format_timedelta': i18n.format_timedelta, } env.globals.update(format_functions) env.filters.update(format_functions) env.globals['url_for'] = url_for after_creation_func = config['after_environment_created'] if after_creation_func: if isinstance(after_creation_func, basestring): after_creation_func = import_string(after_creation_func) after_creation_func(env) environment_created.send(self, environment=env) self.environment = env
def get_app(): app = Flask('kardboard') app.config.from_object('kardboard.default_settings') if os.getenv('KARDBOARD_SETTINGS', None): app.config.from_envvar('KARDBOARD_SETTINGS') app.secret_key = app.config['SECRET_KEY'] app.db = MongoEngine(app) app.jinja_env.add_extension('kardboard.util.Markdown2Extension') app.jinja_env.filters['slugify'] = slugify app.jinja_env.filters['timesince'] = timesince app.jinja_env.filters['timeuntil'] = timeuntil app.jinja_env.filters['jsonencode'] = jsonencode app.jinja_env.globals['newrelic_head'] = newrelic_head app.jinja_env.globals['newrelic_foot'] = newrelic_foot if app.config.get('COMPILE_TEMPLATES', False): compiled_templates = os.path.join( os.path.abspath(os.path.dirname(__file__)), 'compiled_templates') compiled_files = path.path(compiled_templates).files() if len(compiled_files) <= 1: app.jinja_env.compile_templates(compiled_templates, zip=None, py_compile=True) app.jinja_env.loader = ModuleLoader(compiled_templates) configure_logging(app) app.wsgi_app = FixGunicorn(app.wsgi_app) statsd_conf = app.config.get('STATSD_CONF', {}) statsd_connection = statsd.Connection( host=statsd_conf.get('host', '127.0.0.1'), port=statsd_conf.get('port', 8125), sample_rate=statsd_conf.get('sample_rate', 1), ) machine_name = socket.getfqdn().split('.')[0] environment_name = app.config.get('ENV_MAPPING', {}).get(machine_name, 'default') prefix_name = '%s.%s.kardboard' % (environment_name, machine_name) app.statsd = statsd.Client(prefix_name, statsd_connection) if SENTRY_SUPPORT and 'SENTRY_DSN' in app.config.keys(): sentry = Sentry(app) sentry return app
def __init__(self, config): self.config = config self.pages = {} loaders = [FileSystemLoader(str(self.config.theme))] if self.config.compiled_theme is not None: loaders.append(ModuleLoader(str(self.config.compiled_theme))) self.env = Environment(autoescape=True, loader=ChoiceLoader(loaders), undefined=StrictUndefined, extensions=['jinja2.ext.with_']) try: self.describe = subprocess.check_output( ['git', 'describe', '--always'], universal_newlines=True).splitlines()[0] except: self.describe = ''
def create_jinja2_instance(): """Returns the Jinja2 environment. :return: A ``jinja2.Environment`` instance. """ app = Tipfy.app cfg = app.get_config(__name__) templates_compiled_target = cfg.get('templates_compiled_target') use_compiled = not app.dev or cfg.get( 'force_use_compiled') if templates_compiled_target is not None and use_compiled: # Use precompiled templates loaded from a module or zip. loader = ModuleLoader(templates_compiled_target) else: # Parse templates for every new environment instances. loader = FileSystemLoader(cfg.get( 'templates_dir')) if i18n: extensions = ['jinja2.ext.i18n'] else: extensions = [] # Initialize the environment. env = Environment(loader=loader, extensions=extensions) # Add url_for() by default. env.globals['url_for'] = url_for if i18n: # Install i18n. trans = i18n.get_translations env.install_gettext_callables( lambda s: trans().ugettext(s), lambda s, p, n: trans().ungettext(s, p, n), newstyle=True) env.globals.update({ 'format_date': i18n.format_date, 'format_time': i18n.format_time, 'format_datetime': i18n.format_datetime, }) return env
# -*- coding: utf-8 -*- from jinja2 import Environment, FileSystemLoader, ModuleLoader # Compile template Environment(loader=FileSystemLoader('foopkg/templates'))\ .compile_templates("foopkg/compiled/foopkg.zip", py_compile=True) # pyc generate # Environment env = Environment(loader=ModuleLoader("foopkg/compiled/foopkg.zip")) template = env.get_template('0.hello.html') print(template.render(name=u'Петя'))
def load_precompiled(options, tpl, folder): if not isinstance(options, JJCoplilerOptions): options = JJCoplilerOptions(**options) env = create_env(options, ModuleLoader(folder)) return env.get_template(tpl)