python Django的URL的错误处理程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Django的URL的错误处理程序相关的知识,希望对你有一定的参考价值。

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

import logging
from django.conf import settings
from django.template import TemplateDoesNotExist
from django.template import loader
from django.http import HttpResponse

logger = logging.getLogger('django.request')


def handler400(request):
    return _process_request(request, 400)


def handler403(request):
    return _process_request(request, 403)


def handler404(request):
    return _process_request(request, 404)


def handler500(request):
    return _process_request(request, 500)


def _process_request(request, code):
    # type: (request, int) -> request
    template_path = 'common/{}.html'.format(code)
    try:
        template = loader.get_template(template_path)
    except TemplateDoesNotExist:
        msg = 'Template path "{}" does not exists'.format(
            template_path
        )
        logger.warn(msg)

        handler_path = 'django.conf.urls.handler{}'.format(code)
        handler = __import__(handler_path)
        return handler()

    context = {
        'request': request,
        'STATIC_URL': settings.STATIC_URL,
    }
    body = template.render(context, request)
    return HttpResponse(body, code=code)
# -*- coding: utf-8 -*-

from __future__ import unicode_literals

urlpatterns = [
  # ...
]

handler400 = 'apps.common.views.handler400'
handler403 = 'apps.common.views.handler403'
handler404 = 'apps.common.views.handler404'
handler500 = 'apps.common.views.handler500'

以上是关于python Django的URL的错误处理程序的主要内容,如果未能解决你的问题,请参考以下文章

python django -3 视图

Django----路由控制

Django-404错误处理

[Django学习]视图

django -- 视图

30Python之web框架django进阶篇