Django HttpResponse objects and JsonResponse

A: HttpResponse objects Introduction

  1. In front of a class mentioned HttpRequest for receiving the content sent by the client to the server, packaged as a HttpRequest object;
  2. Then the server view function after treatment associated logic, but also need to return to our clients.
  3. HttpResponseBase or its subclasses is returned to the client object; HttpResponse is the most used HttpResponseBase subclass;

Two: HttpResponse common properties

1. content:返回的内容。
2. status_code:返回的HTTP响应状态码。
3. content_type:返回的数据的MIME类型,默认为text/html。浏览器会根据这个属性,来显示数据。
                        如果是text/html,那么就会解析这个字符串,如果text/plain,那么就会显示一个纯文本。
                        常用的Content-Type如下:
        text/html(默认的,html文件)
        text/plain(纯文本)
        text/css(css文件)
        text/javascript(js文件)
        multipart/form-data(文件提交)
        application/json(json传输)
        application/xml(xml文件)
4. 设置请求头:response['X-Access-Token'] = 'xxxx'。

Three: HttpResponse returned text Case Code 1-

def index(request):
    content = "page 404"
    response = HttpResponse(content=content, content_type='text/plain', charset='utf-8')
    response.status_code = 404
    return response

Django HttpResponse objects and JsonResponse


Four: HttpResponse Case Code 2- returned json

def index(request):
    content = {'name': 'huangjiajin', 'age': 18}
    content = json.dumps(content)
    response = HttpResponse(content=content, content_type='application/json')
    response.status_code = 200
    return response

Django HttpResponse objects and JsonResponse


Five: JsonResponse Case Code 3- return json

1. Case

def index(request):
    content = {'name': 'huangjiajin', 'age': 18, 'class': 'k02'}
    return JsonResponse(content)

Django HttpResponse objects and JsonResponse


2. JsonResponse explain

You can click to see into JsonResponse also inherited the HttpResponse object of the second package
Django HttpResponse objects and JsonResponse

Guess you like

Origin blog.51cto.com/jiajinh/2434486