Django中构造响应对象的方式

1 HttpResponse

可以使用django.http.HttpResponse来构造响应对象。

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

也可通过HttpResponse对象属性来设置响应体、响应体数据类型、状态码:

  • content:表示返回的内容。
  • status_code:返回的HTTP响应状态码。
  • content_type:指定返回数据的的MIME类型。

响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:

response = HttpResponse()
response['object'] = 'Python'  # 自定义响应头object, 值为Python

示例:

from django.http import HttpResponse

def demo_view(request):
    return HttpResponse('object python', status=400)
    或者
    response = HttpResponse('object python')
    response.status_code = 400
    response['object'] = 'Python'
    return response

2 HttpResponse子类

Django提供了一系列HttpResponse的子类,可以快速设置状态码

  • HttpResponseRedirect 301
  • HttpResponsePermanentRedirect 302
  • HttpResponseNotModified 304
  • HttpResponseBadRequest 400
  • HttpResponseNotFound 404
  • HttpResponseForbidden 403
  • HttpResponseNotAllowed 405
  • HttpResponseGone 410
  • HttpResponseServerError 500

3 JsonResponse

若要返回json数据,可以使用JsonResponse来构造响应对象,作用:

  • 帮助我们将数据转换为json字符串
  • 设置响应头Content-Type为 application/json
from django.http import JsonResponse

def demo_view(request):
    return JsonResponse({'city': 'beijing', 'subject': 'python'})

   第二个参数为 safe=True , 如果safe=False那可以传入任何能被转换为JSON格式的对象,比如list, tuple, set。

默认的safe 参数是 True. 如果你传入的data数据类型不是字典类型,那么它就会抛出 TypeError的异常。

4 redirect重定向

from django.shortcuts import redirect

def demo_view(request):
    return redirect('/index.html')
posted @ 2018-08-13 20:24  skaarl  阅读(1237)  评论(0编辑  收藏  举报