Django中render、render_to_response、HttpResponse、JsonResponse、Response的使用


https://www.jianshu.com/p/0286b52df32a

Django作為一個后台框架,如何將數據正確的傳遞給前端呢?這得根據前端不同的數據請求方式,正確的使用render、render_to_response、HttpResponse、JsonResponse以及Response

1.1 場景一:傳遞數據給html,並直接渲染到網頁上,使用render

from django.shortcuts import render

def main_page(request):
   data = [1,2,3,4]
   return render(request, 'index.html', {'data': data})

#html使用 {{ }} 來獲取數據
<div>{{ data }}</div>

1.2 場景二:傳遞數據給js,使用render,但數據要json序列化

# -*- coding: utf-8 -*-
 
import json
from django.shortcuts import render
 
def main_page(request):
    list = ['view', 'Json', 'JS']
    return render(request, 'index.html', {
            'List': json.dumps(list),      #序列化操作
        })

#JavaScript部分需要添加safe過濾
var List = {{ List|safe }};

1.3 場景三:傳遞數據給Ajax,使用HttpResponse,且返回到是json序列化字符串

def scene_update_view(request):
    if request.method == "POST":
            name = request.POST.get('name')
            status = 0
            result = "Error!"
            return HttpResponse(json.dumps({
                "status": status,
                "result": result
            }))

# ajax中json字符串轉成對象用JSON.parse(data)

2 render和HttpResponse的區別:

3 render和render_to_response的區別

參考資料:https://www.douban.com/note/278152737/
自django1.3開始:render()方法是render_to_response的一個嶄新的快捷方式,render()會自動使用RequestContext,而render_to_response必須coding出來,如下面舉例中的context_instance=RequestContext(request),所以render()更簡潔。

#render_to_response的使用,必須加上context_instance=RequestContext(request)
return render_to_response('blog_add.html',
{'blog': blog, 'form': form, 'id': id, 'tag': tag},
context_instance=RequestContext(request))

#render的使用,不需要寫RequestContext(request),函數內部會自動加上,多了一個request參數
return render(request, 'blog_add.html', 
{'blog': blog, 'form': form, 'id': id, 'tag': tag})

# render結合locals()以后,會更簡潔,但locals()是直接將函
#數中所有的變量全部傳給模板,可能會傳遞一些多余的參數而
#浪費內存,對可讀性也有影響,故不推薦。
 return render(request, 'blog_add.html',locals())

4 HttpResponse、JsonResponse、Response的使用

參考資料1:http://www.cnblogs.com/LYliangying/articles/9935432.html
參考資料2:https://www.jianshu.com/p/94785f71fdd8

4.1 HTTPResponse(from django.http import HttpResponse):
  • HTTPResponse是由Django創造的,他的返回格式為HTTPResponse(content=響應體,content_type=響應體數據類型,status=狀態碼),可以修改返回的數據類型,適用於返回圖片,視頻,音頻等二進制文件。
  • HTTPResponse默認返回的Content-Type是text/html,也就是字符串類型的返回,所以這段返回值並不是一個標准的json數據,即使是一個長得像json數據的字符串。
  • 在HttpResponse中添加content_type="application/json"的屬性,即可返回標准的json格式
4.2 JsonResponse(from django.http import JsonResponse)
  • JsonResponse是HttpResponse的子類,內部強制做了json轉換,所以返回的一定是json,同時也支持了list的輸出.
    JsonResponse的源碼:
class JsonResponse(HttpResponse):
    def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
                 json_dumps_params=None, **kwargs):
        if safe and not isinstance(data, dict):
            raise TypeError(
                'In order to allow non-dict objects to be serialized set the '
                'safe parameter to False.'
            )
        if json_dumps_params is None:
            json_dumps_params = {}
        kwargs.setdefault('content_type', 'application/json')  #類型轉換
        data = json.dumps(data, cls=encoder, **json_dumps_params)
        super(JsonResponse, self).__init__(content=data, **kwargs)

使用舉例:

from django.shortcuts import render
from django.http import HttpResponse,JsonResponse

# Create your views here.

def index(request):
    data={
        'name':'zhangsan',
        'age':18,
    }
    return JsonResponse(data)   #返回的content_type是application/json

def index(request):
    listdata=[1,2,3,4,5]
    return JsonResponse(listdata)  #報錯,JsonResponse默認接收的是dict類型數據,如果是list類型,需要主動設置safe=False(默認為true)
    return JsonResponse(listdata,safe=False)  #正常輸出
4.3 Response(from rest_framework.response import Response)

Response是rest-framework框架中封裝好的響應對象。
它的返回格式為:   Response(data,status=None,template_name=None,headers=None,content_type=None),
data只需傳遞Python的內建類型數據即可,如果是Django的模型類對象,那么就是用序列化數據傳遞給data
使用舉例:
參考資料:https://www.cnblogs.com/pycode/p/6494633.html

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer


@api_view(['GET', 'POST'])
def snippet_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        snippets = Snippet.objects.all()
        serializer = SnippetSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SnippetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM