一 . 渲染器
https://www.jb51.net/article/166237.htm Django Rest framework解析器和渲染器详解
https://blog.csdn.net/weixin_30359021/article/details/98877731
https://www.cnblogs.com/liwenzhou/p/10267985.html 解析器和渲染器
析器的作用就是服务端接收客户端传过来的数据,把数据解析成自己可以处理的数据。本质就是对请求体中的数据进行解析。
在了解解析器之前,我们要先知道Accept以及ContentType请求头。
Accept是告诉对方我能解析什么样的数据,通常也可以表示我想要什么样的数据。
ContentType是告诉对方我给你的是什么样的数据类型。
解析器工作原理的就是拿到请求的ContentType来判断前端给我的数据类型是什么,然后我们在后端使用相应的解析器去解析数据。
1.局部渲染器(单独给每个视图加)
urls 这是settings的urls
from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url('admin/', admin.site.urls), url(r'^nice/', include('myapp.urls')), ]
urls 这是项目myapp下urls
from django.conf.urls import url,include from myapp.viwes import show urlpatterns = [ url(r'^home/$', show.HomeViwes.as_view()), ]
viwes1
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer class HomeViwes(APIView): renderer_classes = [JSONRenderer,BrowsableAPIRenderer] # 配置局部渲染器 def get(self,request,*args,**kwargs): print(request.version) return Response('哈哈哈哈哈哈') # return HttpResponse("111111111111111111")
viwes2
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.renderers import JSONRenderer,BrowsableAPIRenderer class HomeViwes(APIView): renderer_classes = [JSONRenderer] # 配置局部渲染器 def get(self,request,*args,**kwargs): print(request.version) return Response('哈哈哈哈哈哈') # return HttpResponse("111111111111111111")
settings
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.apps.MyappConfig', 'rest_framework', ]
2.局部渲染器(全局在settings作用于每个视图 url同上)
viwes
from django.shortcuts import render,HttpResponse from rest_framework.views import APIView from rest_framework.response import Response class HomeViwes(APIView): def get(self,request,*args,**kwargs): # print(request.version) return Response('哈哈哈哈哈哈1111111111') # return HttpResponse("111111111111111111")
settings
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES':['rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], }