drf 必需要進行配置python
INSTALLED_APPS = [ ... 'rest_framework' ]
直接在類中進行配置django
from rest_framework.renderers import JSONRenderer # json格式的渲染 from rest_framework.renderers import BrowsableAPIRenderer # 瀏覽器格式的渲染 # JSONParser: json數據 # FormParser: urlencoded # MultiPartParser:form-data class Book(APIView): renderer_classes = [JSONRenderer,]### json格式的渲染 def get(self, request, *args, **kwargs): return Response('get ok')
renderer_classes = [BrowsableAPIRenderer,]###瀏覽器渲染
renderer_classes = [BrowsableAPIRenderer,JSONRenderer] #倆個都有 會選擇第一個
renderer_classes = []#若是爲空 的話就沒法請求
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', # 'rest_framework.renderers.BrowsableAPIRenderer', ], }
開發通常只會配置JSONRenderer,防止破解json
有全局和局部都配置的狀況下,優先走局部配置api
核心:能夠全局和局部配置視圖類支持的結果渲染:默承認以json和頁面渲染,學習該模塊的目的是開發能夠全局只配置json方式渲染瀏覽器
入口:dispatch()方法源碼分析
# 二次處理,渲染模塊 self.response = self.finalize_response(request, response, *args, **kwargs)
if isinstance(response, Response): if not getattr(request, 'accepted_renderer', None): # 內部解析了配置的渲染類 neg = self.perform_content_negotiation(request, force=True) # 解壓賦值 request.accepted_renderer, request.accepted_media_type = neg
def perform_content_negotiation(self, request, force=False): """ Determine which renderer and media type to use render the response. """ # 獲取渲染的方式 renderers = self.get_renderers() conneg = self.get_content_negotiator() try: return conneg.select_renderer(request, renderers, self.format_kwarg) except Exception: if force: # 獲取第一個渲染方式 return (renderers[0], renderers[0].media_type) raise
def get_renderers(self): """ Instantiates and returns the list of renderers that this view can use. """ # 找rederers_classes方法 return [renderer() for renderer in self.renderer_classes]
class APIView(View): # The following policies may be set at either globally, or per-view. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
首先找本身的配置,本身沒有找局部配置,而後找全局配置,最後找django配置的學習