Вопрос по – Как я могу узнать, какую ошибку 500 я получаю в Django?
Когда я захожу на страницу (http://68.123.151.234/static/quickstart.html) в моем приложении Django, обслуживаемом на сервере, порожденном Django, страница выглядит так:
A server error occurred. Please contact the administrator.
И я получаю эту трассировку.
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 153, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 228, in handle_uncaught_exception
return callback(request, **param_dict)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py", line 91, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/defaults.py", line 32, in server_error
t = loader.get_template(template_name) # You need to create a 500.html template.
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 145, in get_template
template, origin = find_template(template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: 500.html
[17/May/2012 11:31:45] "GET /static/quickstart.html HTTP/1.1" 500 59
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 153, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 228, in handle_uncaught_exception
return callback(request, **param_dict)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py", line 91, in _wrapped_view
response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/defaults.py", line 32, in server_error
t = loader.get_template(template_name) # You need to create a 500.html template.
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 145, in get_template
template, origin = find_template(template_name)
File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 138, in find_template
raise TemplateDoesNotExist(name)
TemplateDoesNotExist: 500.html
Эта трассировка только говорит мне, что мне нужен шаблон 500 - не то, что на самом деле ошибка сервера. Как я могу узнать, что была ошибка сервера?
Я проверил документацию Django (https://docs.djangoproject.com/en/1.4/topics/http/views/), который направляет меня на создание шаблона ошибки 500 в качестве потенциального решения. Тем не менее, он не дает никаких инструкций относительно того, как отображать ошибку в таком шаблоне.
DEBUG
установлен вTrue
? Джанго не будет показывать следыDEBUG
установлен вFalse
.
dgel
DEBUG=True
тогда Джанго покажет трассировку.
Как только сайт заработает, вы, вероятно, не захотите отображать трассировку на странице ошибок, поскольку она может содержать конфиденциальную информацию.
Если вы добавите шаблон 500. Затем Django отправит электронное письмо, содержащее данные трассировки, пользователям, указанным в настройке ADMINS.
Смотрите документы наОтчет об ошибках для получения дополнительной информации.
простой 500.html, который удобен и полезен, потенциально может раскрыть что-то чувствительное.
Однако, если целью является ответственная отладка по сети, основной шаблон nondefault500.html для каталога шаблонов вашего сайта будет выглядеть так:
<html><head><body>
<!-- starting with sys.exc_info but hey, it's python -->
Type: {{ type }} <br />
Value: {{ value }} <br />
Traceback: {{ traceback }} <br />
</body></head></html>
и новый обработчик заполнил бы этот контекст следующим образом:
def this_server_error(request, template_name='nondefault500.html'):
"""
500 error handler.
Templates: `500.html`
Context: sys.exc_info() results
"""
t = loader.get_template(template_name) # You need to create a 500.html template.
ltype,lvalue,ltraceback = sys.exc_info()
sys.exc_clear() #for fun, and to point out I only -think- this hasn't happened at
#this point in the process already
return http.HttpResponseServerError(t.render(Context({'type':ltype,'value':lvalue,'traceback':ltraceback})))
и необходимо будет выполнить настройку URLconf,
handler500 = 'mysite.views.this_server_error'