?Django提供了一系列HttpResponse子类来返回各种HTTP响应。如下图所示
下面的代码使用了各种HttpRequest子类返回各种HTTP响应
#chapter5\chapter5\views.py
from django.http import HttpResponseRedirect
from django.http import HttpResponseNotModified
from django.http import HttpResponseForbidden
from django.http import HttpResponseNotAllowed
from django.http import HttpResponsePermanentRedirect
from django.http import HttpResponseServerError
from django.http import HttpResponseGone
from django.http import HttpResponseNotFound
from django.http import HttpResponseBadRequest
def testHttpResponseRedirect(request):
return testHttpResponseRedirect("/admin")
def testHttpResponsePermanentRedirect(request):
return HttpResponsePermanentRedirect("/admin")
def testHttpResponseNotModified(request):
return HttpResponseNotModified()
def testHttpResponseBadRequest(request):
return HttpResponseBadRequest("参数类型错误")
def testHttpResponseNotFound(request):
return HttpResponseNotFound("未找到请求的内容")
def testHttpResponseForbidden(request):
return HttpResponseForbidden("禁止访问请求的内容")
def testHttpResponseNotAllowed(request):
return HttpResponseNotAllowed(['GET',],"不允许使用该方法")
def testHttpResponseGone(request):
return HttpResponseGone("请求的内容已不存在")
def testHttpResponseServerError(request):
return HttpResponseServerError("服务器出错了")
def test(request):
return ()
?相应的URL配置如下:
#chapter5\chapter5\urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('admin',admin.site.urls),
path('re',views.testHttpResponseRedirect),
path('rep', views.testHttpResponsePermanentRedirect),
path('notm',views.testHttpResponseNotModified),
path('badr', views.testHttpResponseBadRequest),
path('forb', views.testHttpResponseForbidden),
path('nota', views.testHttpResponseNotAllowed),
path('gone', views.testHttpResponseGone),
path('serror', views.testHttpResponseServerError),
]
运行项目,在浏览器中访问 http://127.0.0.1:8000/serror,输出结果如图所示。页面中显示了testHttpResponseServerError响应信息。可以看出,为构造函数提供的字符串作为错误提示信息被显示在浏览器中。
?
在运行开发服务器时,可在命令提示符窗口中看到如下的HttResponServerError响应日志信息。
其中的 Internal Server Error? 说明响应信息时内部服务器错误,访问路径为“/serror”,
错误代码为500.
Django并没有为所有的HTTP状态提供处理类。可以使用status参数为HttResponse构造函数指定HTTP状态码,从而返回相应的响应:
#chapter5\chapter5\views.py
from django.http import HttpResponse
def testStatusCode(request):
return HttpResponse(status=401)
#chapter5\chapter5\urls.py
from django.urls import path
from django.contrib import admin
from . import views
urlpatterns = [
path('code', views.testStatusCode),
]
在浏览器中访问“http://127.0.0.1:8000/code”,输出结果如图所示
?
|