python类TemplateDoesNotExist()的实例源码

defaults.py 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 23 收藏 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 文件源码 项目:djanoDoc 作者: JustinChavez 项目源码 文件源码 阅读 41 收藏 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))
views.py 文件源码 项目:djangocms-onepage-example 作者: 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 文件源码 项目:djangocms-onepage-example 作者: thorgate 项目源码 文件源码 阅读 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')

    return HttpResponseServerError(template.render({
        'sentry': sentry_id_from_request(request),
        'error': {
            'title': _('Something went wrong'),
            'message': ('%s' %
                        _('Something went wrong on our side... \n Please hold on while we fix it.')).replace('\n',
                                                                                                             '<br>'),
            'sentry': _('Fault code: #'),
        }
    }))
loader.py 文件源码 项目:django-amp-tools 作者: shtalinberg 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def load_template(self, template_name, template_dirs=None):
        key = self.cache_key(template_name, template_dirs)
        template_tuple = self.template_cache.get(key)

        if template_tuple is TemplateDoesNotExist:
            raise TemplateDoesNotExist('Template not found: %s' % template_name)
        elif template_tuple is None:
            template, origin = self.find_template(template_name, template_dirs)
            if not hasattr(template, 'render'):
                try:
                    template = template_from_string(template)
                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 (later)
                    # of the actual template that does not exist.
                    self.template_cache[key] = (template, origin)

            self.template_cache[key] = (template, None)

        return self.template_cache[key]
dummy.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 34 收藏 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 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 35 收藏 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 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 20 收藏 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 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 27 收藏 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 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 24 收藏 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 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 30 收藏 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))
dummy.py 文件源码 项目:LatinSounds_AppEnviaMail 作者: G3ek-aR 项目源码 文件源码 阅读 24 收藏 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)
adapter.py 文件源码 项目:Provo-Housing-Database 作者: marcopete5 项目源码 文件源码 阅读 36 收藏 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
documents.py 文件源码 项目:balafon 作者: ljean 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def find_template(self, template_type, action_type):
        """look for template"""
        potential_templates = []
        if action_type:
            action_type = slugify(action_type.name)
            potential_templates += [
                u"documents/_{0}_{1}.html".format(action_type, template_type),
            ]

        potential_templates += [
            "documents/_{0}.html".format(template_type),
        ]

        for template_name in potential_templates:
            try:
                get_template(template_name)
                return template_name
            except TemplateDoesNotExist:
                pass

        return None
defaults.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def page_not_found(request, template_name='404.html'):
    """
    Default 404 handler.

    Templates: :template:`404.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    context = {'request_path': request.path}
    try:
        template = loader.get_template(template_name)
        body = template.render(context, request)
        content_type = None             # Django will use DEFAULT_CONTENT_TYPE
    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 http.HttpResponseNotFound(body, content_type=content_type)
defaults.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def bad_request(request, 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')
    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 %}.
static.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 31 收藏 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))
loader.py 文件源码 项目:django-powerpages 作者: Open-E-WEB 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def load_template_source(self, template_name, template_dirs=None):
        """Load templates from powerpages.Page model instances.
        Works only with templates named:
        page/<page_pk>"""
        try:
            namespace, page_pk = template_name.split('/')
        except ValueError:
            pass
        else:
            if namespace == 'page':
                cachekey = cachekeys.template_source(page_pk)
                display_name = "page:%s" % page_pk
                source = cache.get(cachekey)
                if source is None:
                    try:
                        page = Page.objects.get(pk=page_pk)
                    except Page.DoesNotExist:
                        pass
                    else:
                        page_processor = page.get_page_processor()
                        source = page_processor.get_template_source()
                        cache.set(cachekey, source)
                        display_name = "page:%s" % page_pk
                        return source, display_name
                else:
                    return source, display_name
        raise TemplateDoesNotExist(template_name)
django.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_template(self, template_name, dirs=_dirs_undefined):
        try:
            return Template(self.engine.get_template(template_name, dirs), self)
        except TemplateDoesNotExist as exc:
            reraise(exc, self)


问题


面经


文章

微信
公众号

扫码关注公众号