Responses 默认是调用的是 render 实现达到渲染的目的!
前端请求 字段 Accept 指定希望得到的数据类型!或者在 url 后缀之中指定结尾类型,也就是希望返回的类型!
#在setting 指定返回类型 REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) }
在单独的视图指定渲染
from django.contrib.auth.models import User from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView class UserCountView(APIView): """ A view that returns the count of active users in JSON. """ renderer_classes = (JSONRenderer, ) def get(self, request, format=None): user_count = User.objects.filter(active=True).count() content = {'user_count': user_count} return Response(content)
request默认的JSON或表单数据来进行解析,前端请求包含字段Content-Type 设置响应方式,以便后端解析数据!
REST_FRAMEWORK = { #此设置说明只能按照 json 进行数据解析! 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) }
也可以为单个请求类进行指定解析器!(参考文档!)
from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): """ A view that can accept POST requests with JSON content. """ parser_classes = (JSONParser,) def post(self, request, format=None): return Response({'received data': request.data})