Created
May 12, 2017 12:52
-
-
Save DrMartiner/b4ba839b7d96b79cbcf5e4918bfe52f5 to your computer and use it in GitHub Desktop.
Django's URL's error handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment