Ejemplo n.º 1
0
    def render(self, context):
        # flatten the Django Context into a single dictionary.
        context_dict = {}
        for d in context.dicts:
            context_dict.update(d)

        if settings.TEMPLATE_DEBUG:
            from django.test import signals
            self.origin = Origin(self.filename)
            signals.template_rendered.send(sender=self,
                                           template=self,
                                           context=context)

        return super(Template, self).render(context_dict)
Ejemplo n.º 2
0
 def get_template(self, template_name):
     tried = []
     for template_file in self.iter_template_filenames(template_name):
         try:
             with open(template_file, encoding=settings.FILE_CHARSET) as fp:
                 template_code = fp.read()
         except FileNotFoundError:
             tried.append((
                 Origin(template_file, template_name, self),
                 'Source does not exist',
             ))
         else:
             return Template(template_code)
     raise TemplateDoesNotExist(template_name, tried=tried, backend=self)
Ejemplo n.º 3
0
    def get_template(self, template_name, skip=None, **kwargs):
        # find upstream template
        template = None
        tried = []
        for loader in self.loaders:
            try:
                template = loader.get_template(template_name, skip=skip, **kwargs)
                break
            except TemplateDoesNotExist as e:
                tried.extend(e.tried)

        origin = Origin(name=template_name, template_name=template_name, loader=self)

        if not skip:
            try:
                with transaction.atomic():
                    # refresh template objects cache
                    now = timezone.now()
                    if not self.last_checked or (now - self.last_checked).seconds >= REFRESH_INTERVAL:
                        filter_args = {'last_modified__gte': self.last_checked} if self.last_checked else {}
                        for template_obj in TemplateModel.objects.filter(**filter_args).iterator():
                            self.template_objects[template_obj.template_name] = template_obj
                        self.last_checked = now

                    # create / update template object
                    if template_name not in self.template_objects:
                        self.template_objects[template_name] = TemplateModel(template_name=template_name)
                    template_obj = self.template_objects[template_name]
                    default_content = template and template.source
                    if template_obj.default_content != default_content or template_obj.pk is None:
                        template_obj.default_content = default_content
                        template_obj.default_content_changed = (
                            template_obj.original_default_content is not None and
                            template_obj.default_content != template_obj.original_default_content
                        )
                        template_obj.save()

                    # use template with changed content
                    if template_obj.enabled:
                        template = Template(template_obj.changed_content, origin, template_name, self.engine)
            except DatabaseError:
                # IntegrityError: template already created in other thread
                # OperationalError or ProgrammingError (depends on backend): called before (or during) migration
                pass

        if template is None:
            raise TemplateDoesNotExist(template_name, tried=tried)

        return template
Ejemplo n.º 4
0
    def get_template_sources(self, template_name):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set.
        """
        for template_dir in self.get_dirs():
            try:
                name = safe_join(template_dir, template_name)
            except SuspiciousFileOperation:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue

            yield Origin(name=name, template_name=template_name, loader=self)
Ejemplo n.º 5
0
 def get_template_sources(self, template_name):
     """
     A method that takes a template_name and yields Origin instances for
     each possible source.
     """
     domain = settings.site_domain
     template_dir = (Path(settings.BASE_DIR) / 'overload' /
                     domain.replace('.', '-') / 'templates').resolve()
     template_dir = str(template_dir)
     name = safe_join(template_dir, template_name)
     yield Origin(
         name=name,
         template_name=template_name,
         loader=self,
     )
Ejemplo n.º 6
0
 def get_template_sources(self, template_name, template_dirs=None):
     """
     Returns the absolute paths to "template_name" in the specified app.
     If the name does not contain an app name (no colon), an empty list
     is returned.
     The parent FilesystemLoader.load_template_source() will take care
     of the actual loading for us.
     """
     if not ':' in template_name:
         return []
     app_name, template_name = template_name.split(":", 1)
     template_dir = get_app_template_dir(app_name)
     if template_dir:
         return [ Origin(name=join(template_dir, template_name), template_name=template_name, loader=self,)]
     else:
         return []
Ejemplo n.º 7
0
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    template_origin_name = request.GET.get("template_origin", None)
    if template_origin_name is None:
        return HttpResponseBadRequest('"template_origin" key is required')
    try:
        template_origin_name = signing.loads(template_origin_name)
    except Exception:
        return HttpResponseBadRequest('"template_origin" is invalid')
    template_name = request.GET.get("template", template_origin_name)

    final_loaders = []

    for loader_name in settings.TEMPLATE_LOADERS:
        loader = find_template_loader(loader_name)
        if loader is not None:
            final_loaders.append(loader)

    for loader in final_loaders:
        origin = Origin(template_origin_name)
        try:
            source = loader.get_contents(origin)
            break
        except TemplateDoesNotExist:
            pass
    else:
        source = "Template Does Not Exist: %s" % (template_origin_name,)

    try:
        from pygments import highlight
        from pygments.lexers import HtmlDjangoLexer
        from pygments.formatters import HtmlFormatter

        source = highlight(source, HtmlDjangoLexer(), HtmlFormatter())
        source = mark_safe(source)
        source.pygmentized = True
    except ImportError:
        pass

    # Using SimpleTemplateResponse avoids running global context processors.
    return SimpleTemplateResponse(
        "debug_toolbar/panels/template_source.html",
        {"source": source, "template_name": template_name},
    )
Ejemplo n.º 8
0
    def get_template_sources(self, template_name, template_dirs=None):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set.
        """
        if not template_dirs:
            template_dirs = get_directories_in_tethys_apps(('templates', ))
        for template_dir in template_dirs:
            try:
                name = safe_join(template_dir, template_name)
            except SuspiciousFileOperation:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue

            yield Origin(
                name=name,
                template_name=template_name,
                loader=self,
            )


#
# def tethys_apps_template_loader(template_name, template_dirs=None):
#     """
#     Custom Django template loader for tethys apps
#     """
#     # Search for the template in the list of template directories
#     tethysapp_template_dirs = get_directories_in_tethys_apps(('templates',))
#
#     template = None
#
#     for template_dir in tethysapp_template_dirs:
#         template_path = safe_join(template_dir, template_name)
#
#         try:
#             template = open(template_path).read(), template_name
#             break
#         except IOError:
#             pass
#
#     # If the template is still None, raise the exception
#     if not template:
#         raise TemplateDoesNotExist(template_name)
#
#     return template
Ejemplo n.º 9
0
 def get_template_sources(self, template_name, template_dirs=None):
     """
     Returns the absolute paths to "template_name", when appended to
     the FROIDE_THEME app.
     """
     if not template_dirs:
         template_dirs = [theme_template_dir]
     for template_dir in template_dirs:
         try:
             name = safe_join(template_dir, template_name)
         except SuspiciousFileOperation:
             continue
         yield Origin(
             name=name,
             template_name=template_name,
             loader=self,
         )
Ejemplo n.º 10
0
 def get_template_sources(self, template_name):
     bits = template_name.split('/', 2)
     if len(bits) == 3:
         dash_name, panel_name, remainder = bits
         key = os.path.join(dash_name, panel_name)
         if key in panel_template_dirs:
             template_dir = panel_template_dirs[key]
             try:
                 name = safe_join(template_dir, panel_name, remainder)
                 yield Origin(name=name,
                              template_name=template_name,
                              loader=self)
             except UnicodeDecodeError:
                 # The template dir name wasn't valid UTF-8.
                 raise
             except SuspiciousFileOperation:
                 # The joined path was located outside of this template_dir
                 # (it might be inside another one, so this isn't fatal).
                 pass
Ejemplo n.º 11
0
    def render(self):
        if self.is_found:
            log.debug("opening file: " + self.file_name)
            fp = codecs.open(self.file_name, "r", encoding='utf-8')
            log.debug("loading template...")
            # template = Template(fp.read().encode('utf-8'), Origin(self.file_name), self.template_name)
            # sas django 2.2 no longer reqiures bytes so we can go back to just reading it in
            # if this has problems with utf-8 content then do a decode afterwards instead
            template = Template(fp.read(), Origin(self.file_name),
                                self.template_name)
            log.debug("closing file")
            fp.close()

            if template:
                log.debug(
                    "attempting to load context and render the template...")
                return render_page(self.request, template, self.module_name)
            else:
                return None
Ejemplo n.º 12
0
    def get_template_sources(self, template_name):

        # If the cookie doesn't exist, set it to the default theme
        default_theme = get_default_theme()
        theme = getattr(_local, 'theme', default_theme)
        this_theme = find_theme(theme)

        # If the theme is not valid, check the default theme ...
        if not this_theme:
            this_theme = find_theme(get_default_theme())

            # If the theme is still not valid, then move along ...
            # these aren't the templates you are looking for
            if not this_theme:
                pass

        try:
            # To support themes residing outside of Django, use os.path.join to
            # avoid throwing a SuspiciousFileOperation and immediately exiting.
            template_path = os.path.join(
                getattr(settings, 'ROOT_PATH',
                        os.path.abspath('openstack_dashboard')), this_theme[2],
                'templates')
            name = None
            if not template_name.startswith('/'):
                try:
                    name = safe_join(template_path, template_name)
                except SuspiciousFileOperation:
                    name = os.path.join(this_theme[2], 'templates',
                                        template_name)
            elif template_path in template_name:
                name = template_name

            if name:
                yield Origin(name=name,
                             template_name=template_name,
                             loader=self)
        # pylint: disable=try-except-raise
        except UnicodeDecodeError:
            # The template dir name wasn't valid UTF-8.
            raise
Ejemplo n.º 13
0
    def render_template(self, template_string):
        """Used to render an "inner" template, ie one which
        is passed as an argument to spurl"""
        original_autoescape = self.context.autoescape
        self.context.autoescape = False

        template = Template('')
        template_debug = getattr(
            settings, 'TEMPLATE_DEBUG',
            template.engine.debug if hasattr(template, 'engine') else False)
        if template_debug is True:
            origin = Origin(template_string)
        else:
            origin = None

        template.nodelist = self.compile_string(template_string, origin,
                                                template_debug)

        rendered = template.render(self.context)
        self.context.autoescape = original_autoescape
        return rendered
Ejemplo n.º 14
0
    def get_template_sources(self, template_name):

        theme_dirs = [
            utils.CURRENT_THEME,
            'default'
        ]

        for template_dir in theme_dirs:
            # import pdb ; pdb.set_trace()
            try:
                name = safe_join(self.theme_root, template_dir, template_name)
            except Exception as e:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue

            yield Origin(
                name=name,
                template_name=template_name,
                loader=self,
            )
Ejemplo n.º 15
0
    def get_template_sources(self, template_name, template_dirs=None):
        """
        Returns the absolute paths to "template_name", when appended to each
        directory in "template_dirs". Any paths that don't lie inside one of
        the template dirs are excluded from the result set, for
        security reasons.
        """
        if not template_dirs:
            template_dirs = self.default_template_dirs

        try:
            use_origin = self.get_contents is not None
        except AttributeError:
            use_origin = False

        for template_dir in template_dirs:
            try:
                template_parts = get_template_name(template_dir, template_name)
                if not template_parts:
                    continue
                name = safe_join(*template_parts)

                if use_origin:
                    yield Origin(
                        name=name,
                        template_name=template_name,
                        loader=self,
                    )
                else:
                    yield name

            except UnicodeDecodeError:
                # The template dir name was a bytestring that
                # wasn't valid UTF-8.
                raise
            except SuspiciousFileOperation:
                # The joined path was located outside of this particular
                # template_dir (it might be inside another one, so this isn't
                # fatal).
                pass
Ejemplo n.º 16
0
    def get_template_sources(self, template_name, template_dirs=None):
        """Make the loader layer aware"""

        if not template_dirs:
            template_dirs = self.get_dirs()
        layers = list(get_current_layer_stack(get_current_request()))
        layers.reverse()
        for template_dir in template_dirs:
            for layer in layers:
                l_template_name = os.path.join(layer, template_name)
                try:
                    name = safe_join(template_dir, l_template_name)
                except SuspiciousFileOperation:
                    # The joined path was located outside of this template_dir
                    # (it might be inside another one, so this isn"t fatal).
                    continue

                yield Origin(
                    name=name,
                    template_name=template_name,
                    loader=self,
                )
Ejemplo n.º 17
0
    def get_template(self, template_name):
        tried = []
        for template_file in self.iter_template_filenames(template_name):
            try:
                with io.open(template_file,
                             encoding=settings.FILE_CHARSET) as fp:
                    template_code = fp.read()
            except IOError as e:
                if e.errno == errno.ENOENT:
                    tried.append((
                        Origin(template_file, template_name, self),
                        'Source does not exist',
                    ))
                    continue
                raise

            return Template(template_code)

        else:
            raise TemplateDoesNotExist(template_name,
                                       tried=tried,
                                       backend=self)
Ejemplo n.º 18
0
 def get_template_sources(self, template_name, template_dirs=None):
     """
     Returns the absolute paths to "template_name" in the specified app.
     If the name does not contain an app name (no colon), an empty list
     is returned.
     The parent FilesystemLoader.load_template_source() will take care
     of the actual loading for us.
     """
     if not ':' in template_name:
         return []
     app_name, template_name = template_name.split(":", 1)
     template_dir = get_app_template_dir(app_name)
     if template_dir:
         try:
             from django.template import Origin
             origin = Origin(
                 name=join(template_dir, template_name),
                 template_name=template_name,
                 loader=self,
             )
         except (ImportError, TypeError):
             origin = join(template_dir, template_name)
         return [origin]
     return []
Ejemplo n.º 19
0
 def get_template_sources(self, template_name, template_dirs=None):
     """
     Returns the absolute paths to "template_name", when appended to each
     directory in "template_dirs". Any paths that don't lie inside one of the
     template dirs are excluded from the result set, for security reasons.
     """
     if not template_dirs:
         template_dirs = self.get_dirs()
     for template_dir in template_dirs:
         try:
             name = safe_join(template_dir, template_name)
         except SuspiciousFileOperation:
             # The joined path was located outside of this template_dir
             # (it might be inside another one, so this isn't fatal).
             pass
         else:
             if Origin:
                 yield Origin(
                     name=name,
                     template_name=template_name,
                     loader=self,
                 )
             else:
                 yield name
Ejemplo n.º 20
0
    def get_template_sources(self, template_name):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set.
        """
        if hasattr(self, 'dirs') and self.dirs is not None:
            dirs = self.dirs
        else:
            dirs = self.engine.dirs

        # print 'DIRS IN GET_TEMPLATE_SOURCES() IS, ', dirs
        for template_dir in dirs:
            try:
                name = safe_join(template_dir, MOCKUPS_DIR, template_name)
            except SuspiciousFileOperation:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue
            yield Origin(
                name=name,
                template_name=template_name,
                loader=self,
            )
Ejemplo n.º 21
0
 def get_template_sources(self, template_name):
     yield Origin(name='entrydetailloader',
                  template_name=template_name,
                  loader=self)
Ejemplo n.º 22
0
 def get_template_sources(self, template_name):
     yield Origin(name='voidloader',
                  template_name=template_name,
                  loader=self)
Ejemplo n.º 23
0
 def make_origin(engine, name, loader, template_name, dirs):
     return Origin(name=name, template_name=template_name, loader=loader)
Ejemplo n.º 24
0
 def get_template_sources(self, template_name, template_dirs=None):
     yield Origin(
         name=template_name,
         template_name=template_name,
         loader=self,
     )
Ejemplo n.º 25
0
 def _make_origin(self):
     return Origin("Commons Test", lambda x, y: ("<string>", "<string>"),
                   "commons", [])
Ejemplo n.º 26
0
def template_source(request):
    """
    Return the source of a template, syntax-highlighted by Pygments if
    it's available.
    """
    template_origin_name = request.GET.get('template_origin', None)
    if template_origin_name is None:
        return HttpResponseBadRequest('"template_origin" key is required')
    try:
        template_origin_name = signing.loads(template_origin_name)
    except Exception:
        return HttpResponseBadRequest('"template_origin" is invalid')
    template_name = request.GET.get('template', template_origin_name)

    final_loaders = []
    loaders = Engine.get_default().template_loaders

    for loader in loaders:
        if loader is not None:
            # When the loader has loaders associated with it,
            # append those loaders to the list. This occurs with
            # django.template.loaders.cached.Loader
            if hasattr(loader, 'loaders'):
                final_loaders += loader.loaders
            else:
                final_loaders.append(loader)

    for loader in final_loaders:
        if Origin:  # django>=1.9
            origin = Origin(template_origin_name)
            try:
                source = loader.get_contents(origin)
                break
            except TemplateDoesNotExist:
                pass
        else:  # django<1.9
            try:
                source, _ = loader.load_template_source(template_name)
                break
            except TemplateDoesNotExist:
                pass
    else:
        source = "Template Does Not Exist: %s" % (template_origin_name, )

    try:
        from pygments import highlight
        from pygments.lexers import HtmlDjangoLexer
        from pygments.formatters import HtmlFormatter

        source = highlight(source, HtmlDjangoLexer(), HtmlFormatter())
        source = mark_safe(source)
        source.pygmentized = True
    except ImportError:
        pass

    # Using SimpleTemplateResponse avoids running global context processors.
    return SimpleTemplateResponse('debug_toolbar/panels/template_source.html',
                                  {
                                      'source': source,
                                      'template_name': template_name
                                  })
Ejemplo n.º 27
0
 def origin(self):
     return Origin(self.filename)
Ejemplo n.º 28
0
 def get_template_sources(self, template_name):
     if template_name == "channels.html":
         yield Origin(name=template_name,
                      template_name=template_name,
                      loader=self)
Ejemplo n.º 29
0
 def make_origin(display_name, loader, name, dirs):
     return Origin(
         name=display_name,
         template_name=name,
         loader=loader,
     )
Ejemplo n.º 30
0
 def get_template_sources(self, template_name):
     _thread_locals.templates = getattr(_thread_locals, 'templates', []) + [
         template_name,
     ]
     yield Origin(None)