python类TemplateDoesNotExist()的实例源码

dummy.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 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)
eggs.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name)
base.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def bad_request(request, exception, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
defaults.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def permission_denied(request, exception, template_name='403.html'):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )
static.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine().from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c))
base.py 文件源码 项目:django-herald 作者: worthwhile 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def render(self, render_type, context):
        """
        Renders the template

        :param render_type: the content type to render
        :param context: context data dictionary
        :return: the rendered content
        """

        assert render_type in self.render_types, 'Invalid Render Type'

        try:
            content = render_to_string('herald/{}/{}.{}'.format(
                render_type,
                self.template_name,
                'txt' if render_type == 'text' else render_type
            ), context)
        except TemplateDoesNotExist:
            content = None
            if settings.DEBUG:
                raise

        return content
templates.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_template_source(name, dirs=None):
    """Retrieves the template's source contents.

    :param name: Template's filename, as passed to the template loader.
    :param dirs: list of directories to optionally override the defaults.
    :return: tuple including file contents and file path.
    """
    loaders = []
    for loader in Engine.get_default().template_loaders:
        # The cached loader includes the actual loaders underneath
        if hasattr(loader, 'loaders'):
            loaders.extend(loader.loaders)
        else:
            loaders.append(loader)

    for loader in loaders:
        try:
            return loader.load_template_source(name, template_dirs=dirs)
        except TemplateDoesNotExist:
            pass

    raise TemplateDoesNotExist(name)
views.py 文件源码 项目:no-design-slack-clone 作者: metsavaht 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
views.py 文件源码 项目:no-design-slack-clone 作者: metsavaht 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def server_error(request, template_name='500.html'):
    if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
        return JsonResponse({
            'sentry': sentry_id_from_request(request),
            'error': {
                'title': _('Something went wrong'),
            }
        }, status=500)

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')

    message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': message,
            'sentry': _('Fault code: #'),
        }
    }))
adapter.py 文件源码 项目:django-twilio-tfa 作者: rtindru 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def add_message(self, request, level, message_template,
                    message_context=None, extra_tags=''):
        """
        Wrapper of `django.contrib.messages.add_message`, that reads
        the message text from a template.
        """
        if 'django.contrib.messages' in settings.INSTALLED_APPS:
            try:
                if message_context is None:
                    message_context = {}
                message = render_to_string(message_template,
                                           message_context).strip()
                if message:
                    messages.add_message(request, level, message,
                                         extra_tags=extra_tags)
            except TemplateDoesNotExist:
                pass
views.py 文件源码 项目:django-project-template 作者: thorgate 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def page_not_found(request, template_name='404.html'):
    context = {
        'request_path': request.path,
        'error': {
            'title': _('Page not found'),
            'message': _("We tried but couldn't find this page, sorry."),
        },
    }

    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None

    except TemplateDoesNotExist:
        template = Engine().from_string(
            '<h1>Not Found</h1>'
            '<p>The requested URL {{ request_path }} was not found on this server.</p>')
        body = template.render(Context(context))
        content_type = 'text/html'

    return HttpResponseNotFound(body, content_type=content_type)
views.py 文件源码 项目:django-project-template 作者: thorgate 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def server_error(request, template_name='500.html'):
    if request.is_ajax() or request.META.get('HTTP_ACCEPT', 'text/plain') == 'application/json':
        return JsonResponse({
            'sentry': sentry_id_from_request(request),
            'error': {
                'title': _('Something went wrong'),
            }
        }, status=500)

    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')

    message = _('Something went wrong on our side... \n Please hold on while we fix it.').replace('\n', '<br>')
    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': message,
            'sentry': _('Fault code: #'),
        }
    }))
dummy.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 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)
eggs.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name)
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
defaults.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_400_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
defaults.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    Templates: :template:`403.html`
    Context: None

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )
static.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def directory_index(path, fullpath):
    try:
        t = loader.select_template([
            'static/directory_index.html',
            'static/directory_index',
        ])
    except TemplateDoesNotExist:
        t = Engine(libraries={'i18n': 'django.templatetags.i18n'}).from_string(DEFAULT_DIRECTORY_INDEX_TEMPLATE)
    files = []
    for f in os.listdir(fullpath):
        if not f.startswith('.'):
            if os.path.isdir(os.path.join(fullpath, f)):
                f += '/'
            files.append(f)
    c = Context({
        'directory': path + '/',
        'file_list': files,
    })
    return HttpResponse(t.render(c))
views.py 文件源码 项目:telemetry-analysis-service 作者: mozilla 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
    """
    500 error handler.

    :template: :file:`500.html`
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_500_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html')
    return http.HttpResponseServerError(template.render(request=request))


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.
views.py 文件源码 项目:telemetry-analysis-service 作者: mozilla 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
    """
    Permission denied (403) handler.

    :template: :file:`403.html`

    If the template does not exist, an Http403 response containing the text
    "403 Forbidden" (as per RFC 7231) will be returned.
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        if template_name != ERROR_403_TEMPLATE_NAME:
            # Reraise if it's a missing custom template.
            raise
        return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html')
    return http.HttpResponseForbidden(
        template.render(request=request, context={'exception': force_text(exception)})
    )
django.py 文件源码 项目:deb-python-django-compressor 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_nodelist(self, node, original, context):
        if isinstance(node, ExtendsNode):
            try:
                if context is None:
                    context = Context()
                context.template = original
                return handle_extendsnode(node, context)
            except template.TemplateSyntaxError as e:
                raise TemplateSyntaxError(str(e))
            except template.TemplateDoesNotExist as e:
                raise TemplateDoesNotExist(str(e))

        # Check if node is an ```if``` switch with true and false branches
        nodelist = []
        if isinstance(node, Node):
            for attr in node.child_nodelists:
                nodelist += getattr(node, attr, [])
        else:
            nodelist = getattr(node, 'nodelist', [])
        return nodelist
dummy.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 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)
eggs.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name)
base.py 文件源码 项目:liberator 作者: libscie 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
loaders.py 文件源码 项目:django-label-loaders 作者: maykinmedia 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """
        Returns a tuple containing the source and origin for the given template
        name.

        Dispatch this to the underlying loaders.
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )

        site = Site.objects.get_current()
        label = settings.SITELABELS.label_from_site(site)

        # put the prefixed template in front of the possible templates
        names = [os.path.join(label, template_name), template_name]
        for name in names:  # always try to load the label-specific version first, independent from the loader
            for loader in self.loaders:
                try:
                    return loader.load_template_source(name, template_dirs=template_dirs)
                except TemplateDoesNotExist:
                    pass
        raise TemplateDoesNotExist("Tried %s" % ', '.join(names))
dummy.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 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)
eggs.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """
        Loads templates from Python eggs via pkg_resource.resource_string.

        For every installed app, it tries to get the resource (app, template_name).
        """
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name)
base.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def load_template(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template() method is deprecated. Use get_template() '
            'instead.', RemovedInDjango20Warning,
        )
        source, display_name = self.load_template_source(
            template_name, template_dirs,
        )
        origin = Origin(
            name=display_name,
            template_name=template_name,
            loader=self,
        )
        try:
            template = Template(source, origin, template_name, self.engine)
        except TemplateDoesNotExist:
            # If compiling the template we found raises TemplateDoesNotExist,
            # back off to returning the source and display name for the
            # template we were asked to load. This allows for correct
            # identification of the actual template that does not exist.
            return source, display_name
        else:
            return template, None
defaults.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def bad_request(request, exception, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    # No exception content is passed to the template, to not disclose any sensitive information.
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}.


问题


面经


文章

微信
公众号

扫码关注公众号