Example #1
0
 def get_source(self, environment, template):
     try:
         cookbook, name = template.split('/', 1)
     except ValueError:
         raise Fail(
             "[Template(%s)] Path must include cookbook name (e.g. 'nginx/nginx.conf.j2')"
             % template)
     cb = self.env.cookbooks[cookbook]
     path = os.path.join(cb.path, "templates", name)
     if not os.path.exists(path):
         raise TemplateNotFound("%s at %s" % (template, path))
     mtime = os.path.getmtime(path)
     with open(path, "rb") as fp:
         source = fp.read().decode('utf-8')
     return source, path, lambda: mtime == os.path.getmtime(path)
Example #2
0
    def get_source(self, environment, template):
        try:
            data = get_repo_blob_data_cached(self.repo, template,
                                             self.commit_sha)
        except ObjectDoesNotExist:
            raise TemplateNotFound(template)

        source = data.decode('utf-8')

        def is_up_to_date():
            # There's not much point to caching here, because we create
            # a new loader for every request anyhow...
            return False

        return source, None, is_up_to_date
Example #3
0
    def render_template(cls, template_name, variables=None):
        if variables is None:
            variables = {}
        env = Environment(
            loader=FileSystemLoader(app_settings['template_path']))
        jcf = JinjaCustomFilter()
        env.filters['debug'] = jcf.debug
        env.filters['repr'] = jcf.repr
        try:
            template = env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)

        content = template.render(variables)
        return content
Example #4
0
    def get_source(self, environment: Environment,
                   template: str) -> Tuple[str, str, Callable]:
        if template.startswith('!'):
            # search a template from ``system_templates_paths``
            loaders = self.sysloaders
            template = template[1:]
        else:
            loaders = self.loaders

        for loader in loaders:
            try:
                return loader.get_source(environment, template)
            except TemplateNotFound:
                pass
        raise TemplateNotFound(template)
Example #5
0
        def get_source(self, environment, template_name):
            # absolute path
            if template_name.startswith(os.path.sep):
                path = template_name
            # relative path
            else:
                basedir = self.env.config.basedir
                path = os.path.join(basedir, "templates", template_name)

            if not os.path.exists(path):
                raise TemplateNotFound("%s at %s" % (template_name, path))
            mtime = os.path.getmtime(path)
            with open(path, "rb") as fp:
                source = fp.read().decode('utf-8')
            return source, path, lambda: mtime == os.path.getmtime(path)
Example #6
0
    def render_template(self, template_name, **kwargs):
        template_dirs = []
        if self.settings.get('template_path', ''):
            template_dirs.append(
                self.settings["template_path"]
            )

        env = Environment(loader=FileSystemLoader(template_dirs))

        try:
            template = env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)
        content = template.render(kwargs)
        return content
Example #7
0
	def render_template(self, template_name, **kwargs):
		template_dirs = ["./views"]
		if self.settings.get('template_path', ''):
			template_dirs.append(
				self.settings["template_path"]
			)
			
		env = Environment(loader=FileSystemLoader(template_dirs),extensions=['jinja2.ext.loopcontrols'])
		
		try:
			template = env.get_template(template_name)
		except TemplateNotFound:
			raise TemplateNotFound(template_name)
		content = template.render(kwargs)
		return content
Example #8
0
 def get_theme_template(
     self, environment: Environment, template: str
 ) -> Tuple[str, str, Callable]:
     """Get the source for a theme template, or a template in an inherited
     theme.
     """
     path = self.theme.templates_dir.joinpath(template)
     if path.is_file():
         return self._return_source(path)
     elif self.inherited_loader is not None:
         return self.inherited_loader.get_theme_template(
             environment, template
         )
     else:
         raise TemplateNotFound(template)
Example #9
0
    def get_source(self, environment, template):
        tpl = os.path.join('html', template)

        path = self.get_template_path(tpl)
        if not path:
            raise TemplateNotFound(tpl)

        mtime = os.path.getmtime(path)
        unchanged = lambda: (path == self.get_template_path(tpl) and mtime ==
                             os.path.getmtime(path))

        with file(path) as f:
            source = f.read().decode('utf-8')

        return source, path, unchanged
Example #10
0
    def _get_source_fast(self, environment, template):
        num_priors = 0
        template, expected_priors = parse_template(template)

        for srcobj, loader in self._iter_loaders(template):
            try:
                rv = loader.get_source(environment, template)
            except TemplateNotFound:
                continue

            if expected_priors - num_priors == 0:
                return rv
            num_priors += 1

        raise TemplateNotFound(template)
Example #11
0
 def render_template(self, template_name, **kwargs):
     template_dirs = []
     if self.settings.get('template_path', ''):
         template_dirs.append(
             self.settings["template_path"]
         )
     template_name = '%s.tpl' % template_name
     env = Environment(loader=FileSystemLoader(template_dirs))
     env.filters['jsond'] = json.dumps
     env.filters['linkify'] = bleach.linkify
     try:
         template = env.get_template(template_name)
     except TemplateNotFound:
         raise TemplateNotFound(template_name)
     content = template.render(kwargs)
     return content
Example #12
0
    def render_template(self, template_name, **kwargs):
        template_dir = os.environ['TEMPLATE_FOLDER']

        env = Environment(loader=FileSystemLoader(template_dir))

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

        self.dict_object.update(**kwargs)

        try:
            template = env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)
        content = template.render(self.dict_object)
        return content
Example #13
0
    def get_source(self, environment, template):
        filename = os.path.join(self.scenario_dir, template, 'scenario.html')
        try:
            with open(filename) as f:
                contents = f.read()
            mtime = os.path.getmtime(filename)
        except (IOError, OSError):
            raise TemplateNotFound(template)

        def uptodate():
            try:
                os.path.getmtime(filename) == mtime
            except OSError:
                return False

        return contents, template, uptodate
Example #14
0
    def get_source(self, environment, template):
        template = os.path.join('html', template)
        path, mt = self.config.data_file_and_mimetype('html_theme', template)
        if not path:
            raise TemplateNotFound(template)

        mtime = os.path.getmtime(path)

        def unchanged():
            return (path == self.config.data_file_and_mimetype(
                'html_theme', template) and mtime == os.path.getmtime(path))

        with file(path) as f:
            source = f.read().decode('utf-8')

        return source, path, unchanged
Example #15
0
    def get_source(self, env, template):
        filename = self.get_filename(template)
        if not filename:
            raise TemplateNotFound(template)

        if not env.auto_reload and filename in env.cache:
            # Do not reload template source if it is not necessary
            return '', filename, lambda: True

        log.debug('Load template source: %s', template)
        with open(filename, encoding='utf-8') as f:
            source = f.read()
        if self.lstrip:
            source = '\n'.join(row.lstrip() for row in source.split('\n'))
        mtime = getmtime(filename)
        return source, filename, lambda: mtime == getmtime(filename)
Example #16
0
 def get_source(self, environment, template):
     name = template
     loader = None
     try:
         module, name = template.split('/', 1)
         loader = self.app.modules[module].jinja_loader
     except (ValueError, KeyError):
         pass
     if loader is None:
         loader = self.app.jinja_loader
     try:
         return loader.get_source(environment, name)
     except TemplateNotFound:
         # re-raise the exception with the correct fileame here.
         # (the one that includes the prefix)
         raise TemplateNotFound(template)
Example #17
0
 def _get_randomized_source(self,
                            name: str,
                            rand: Optional[random.Random] = None) -> str:
     """Get the template source, handle necessary randomization."""
     try:
         source = self.mapping[name]
     except KeyError:
         raise TemplateNotFound(name)
     if isinstance(source, list):
         _validate_randomizable_source(name, source)
         values = [s[0] if isinstance(s, list) else s for s in source]
         weights = [s[1] if isinstance(s, list) else 1 for s in source]
         if rand is None:
             rand = random.Random()
         source = rand.choices(values, weights)[0]
     return source
Example #18
0
    def get_source(self, environment, template):
        template_path_parts = template.split("#", 2)

        server_versions = ({
            'name': "9.6_plus",
            'number': 90600
        }, {
            'name': "9.5_plus",
            'number': 90500
        }, {
            'name': "9.4_plus",
            'number': 90400
        }, {
            'name': "9.3_plus",
            'number': 90300
        }, {
            'name': "9.2_plus",
            'number': 90200
        }, {
            'name': "9.1_plus",
            'number': 90100
        }, {
            'name': "9.0_plus",
            'number': 90000
        }, {
            'name': "default",
            'number': 0
        })

        if len(template_path_parts) == 1:
            return super(VersionedTemplateLoader,
                         self).get_source(environment, template)
        else:
            for server_version in server_versions:
                path_start, specified_version_number, file_name = template_path_parts

                if server_version['number'] > int(specified_version_number):
                    continue

                template_path = path_start + '/' + server_version[
                    'name'] + '/' + file_name
                try:
                    return super(VersionedTemplateLoader,
                                 self).get_source(environment, template_path)
                except TemplateNotFound:
                    continue
            raise TemplateNotFound(template)
    def render_template(self, template, **kwargs):
        template_dirs = self.template_dirs
        if self.settings.get("template_path", ""):
            # insert at beginnging
            template_dirs.insert(0, self.settings["template_path"])
        env = Environment(loader=FileSystemLoader(template_dirs))

        try:
            template = env.get_template(self.template)
        except TemplateNotFound:
            raise TemplateNotFound(self.template)

        kwargs["current_user"] = self.current_user if self.current_user else ""
        kwargs["basepath"] = self.basepath
        kwargs["wspath"] = self.wspath
        content = template.render(**kwargs)
        return content
Example #20
0
def _reload_template(app, key):
    from application.extensions import redis
    lm_key = "{}:lm".format(key)
    path_key = "{}:path".format(key)

    path = redis.get(path_key)
    last_modified = redis.get(lm_key)

    if not path or not last_modified:
        app.logger.error("template path: {}".format(path))
        app.logger.error("template last modified: {}".format(last_modified))
        raise TemplateNotFound(key)
    curr_last_modified = time.ctime(os.path.getmtime(path))
    if last_modified != curr_last_modified:
        with open(path, 'r') as f:
            data = f.read()
            redis.set(key, data)
            redis.set(lm_key, curr_last_modified)
Example #21
0
    def render_template(self, template_name, **kwargs):
        template_dirs = []
        if self.settings.get('template_path', ''):
            template_dirs.append(self.settings["template_path"])

        env = Environment(loader=FileSystemLoader(template_dirs))
        env.tests['rs_is_lived'] = rs_is_lived
        env.tests['user_is_manager'] = user_is_manager
        env.filters['timestamptodate'] = timestamptodate
        env.filters['bytesformat'] = bytesformat
        env.filters['format_rs_str'] = format_rs_str

        try:
            template = env.get_template(template_name)
        except TemplateNotFound:
            raise TemplateNotFound(template_name)
        content = template.render(kwargs)
        return content
    def render_template(self, template_name, variables={}):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        template_path = dir_path + "/templates"
        template_dirs = [template_path]

        env = Environment(loader=FileSystemLoader(template_dirs),
                          auto_reload=True,
                          autoescape=False)
        env.globals['S'] = '/static'

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

        content = template.render(variables)

        return content
Example #23
0
    def get_source(self, environment, template):
        if LOCAL:
            # during local development, templates are files and we want "uptodate" feature
            return FileSystemLoader.get_source(self, environment, template)

        # on production server template may come from zip file
        for searchpath in self.searchpath:
            filename = os.path.join(searchpath, template)
            contents = universal_read(filename)
            if contents is None:
                continue
            contents = contents.decode(self.encoding)

            def uptodate():
                return True

            return contents, filename, uptodate
        raise TemplateNotFound(template)
Example #24
0
    def _do_get_source(self, environment, template):
        path = join(self.path, template)
        ok = exists(path)

        if not ok:
            for ext in C.YAML_EXTS:
                p = path + ext
                if exists(p):
                    path = p
                    ok = True
                    break

        if not ok:
            raise TemplateNotFound(template)
        mtime = getmtime(path)
        with file(path) as f:
            source = f.read().decode('utf-8')
        return source, path, lambda: mtime == getmtime(path)
Example #25
0
 def get_source(self, environment, template):
     template = posixpath.normpath(template)
     if template.startswith('../'):
         raise TemplateNotFound(template)
     loader = None
     try:
         module, name = template.split('/', 1)
         loader = self.app.modules[module].jinja_loader
     except (ValueError, KeyError):
         pass
     # if there was a module and it has a loader, try this first
     if loader is not None:
         try:
             return loader.get_source(environment, name)
         except TemplateNotFound:
             pass
     # fall back to application loader if module failed
     return self.app.jinja_loader.get_source(environment, template)
Example #26
0
    def get_source(self, environment: Environment, template: str) -> Tuple[str, str, Callable]:
        for searchpath in self.searchpath:
            filename = path.join(searchpath, template)
            f = open_if_exists(filename)
            if f is None:
                continue
            with f:
                contents = f.read().decode(self.encoding)

            mtime = path.getmtime(filename)

            def uptodate() -> bool:
                try:
                    return path.getmtime(filename) == mtime
                except OSError:
                    return False
            return contents, filename, uptodate
        raise TemplateNotFound(template)
Example #27
0
    def _get_source_explained(self, environment, template):
        attempts = []
        trv = None

        for srcobj, loader in self._iter_loaders(template):
            try:
                rv = loader.get_source(environment, template)
                if trv is None:
                    trv = rv
            except TemplateNotFound:
                rv = None
            attempts.append((loader, srcobj, rv))

        from .debughelpers import explain_template_loading_attempts
        explain_template_loading_attempts(self.app, template, attempts)

        if trv is not None:
            return trv
        raise TemplateNotFound(template)
Example #28
0
    def render_template(self, template, **kwargs):
        if hasattr(self, 'template_dirs'):
            template_dirs = self.template_dirs
        else:
            template_dirs = []

        if self.settings.get('template_path', ''):
            template_dirs.append(self.settings["template_path"])
        env = Environment(loader=FileSystemLoader(template_dirs))

        try:
            template = env.get_template(self.template)
        except TemplateNotFound:
            raise TemplateNotFound(self.template)

        kwargs['current_user'] = self.current_user.decode(
            'utf-8') if self.current_user else ''
        content = template.render(**kwargs)
        return content
    def get_source(self, environment, template):
        for searchpath in self.searchpath:
            filename = path.join(searchpath, template)
            f = open_if_exists(filename)
            if f is None:
                continue
            try:
                contents = f.read().decode(self.encoding)
            finally:
                f.close()

            mtime = path.getmtime(filename)
            def uptodate():
                try:
                    return path.getmtime(filename) == mtime
                except OSError:
                    return False
            return contents, filename, uptodate
        raise TemplateNotFound(template)
Example #30
0
 def get_source(self, environment, template):
     # If template name in Jinja's "extends" is prepended with "!"
     # Sphinx skips project's template paths.
     # In BuiltinTemplateLoader self.templatepathlen is used to remove
     # project's template paths and leave only Sphinx's paths.
     # This hack should leave the last path, so "!layout.html" will find
     # the template from Fityk. To avoid recursion, Fityk template
     # is not using "!".
     loaders = self.loaders
     # exclamation mark starts search from theme
     if template.startswith("!"):
         loaders = loaders[self.templatepathlen - 1:]
         template = template[1:]
     for loader in loaders:
         try:
             return loader.get_source(environment, template)
         except TemplateNotFound:
             pass
     raise TemplateNotFound(template)