Python 如何在 Django 中触发 500 错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24660406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I trigger a 500 error in Django?
提问by User
I'm trying to setup email error logging and I want to test it.
我正在尝试设置电子邮件错误日志,我想对其进行测试。
Whats an easy way to trigger a 500 error in Django? This surprisingly has not been discussed here yet.
在 Django 中触发 500 错误的简单方法是什么?令人惊讶的是,这里尚未讨论这一点。
采纳答案by agconti
A test view like this will work:
像这样的测试视图将起作用:
from django.http import HttpResponse
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponse(status=500)
or use the baked in error class:
或使用烘焙错误类:
from django.http import HttpResponseServerError
def my_test_500_view(request):
# Return an "Internal Server Error" 500 response code.
return HttpResponseServerError()
回答by Shaun Overton
Raising an appropriate Exception
is the most robust way to test this. Returning an HttpResponse
of any variety, as in @agconti 's answer, will not allow you to test the behavior of error handling. You'll just see a blank page. Raising an exception triggers both the correct response code and the internal Django behavior you expect with a "real" error.
提出适当Exception
的方法是测试这一点的最可靠方法。返回HttpResponse
任何种类的 ,如@agconti 的回答,将不允许您测试错误处理的行为。你只会看到一个空白页。引发异常会触发正确的响应代码和您期望的“真实”错误的内部 Django 行为。
Response code 500 represents the server not knowing what to do. The easiest way is to write into your test or test-view raise Exception('Make response code 500!')
.
响应代码 500 表示服务器不知道该做什么。最简单的方法是写入您的 test 或 test-view raise Exception('Make response code 500!')
。
Most other errors should be raised with exceptions designed to trigger specific response codes. Here's the complete list of Django exceptionsthat you might raise.
大多数其他错误应该与旨在触发特定响应代码的异常一起引发。这是您可能引发的 Django 异常的完整列表。