rest-framework之響應器(渲染器)
阿新 • • 發佈:2018-12-21
col sta false 請求 books elf 響應 lte row
https://www.cnblogs.com/liuqingzheng/articles/9766413.html
一 作用
根據 用戶請求URL 或 用戶可接受的類型,篩選出合適的 渲染組件。
用戶請求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.json
二 內置渲染器
顯示json格式:JSONRenderer
訪問URL:
- http://127.0.0.1:8000/test/?format=json
- http://127.0.0.1:8000/test.json
- http://127.0.0.1:8000/test/
默認顯示格式:BrowsableAPIRenderer(可以修改它的html文件)
訪問URL:
- http://127.0.0.1:8000/test/?format=api
- http://127.0.0.1:8000/test.api
- http://127.0.0.1:8000/test/
表格方式:AdminRenderer
訪問URL:
- http://127.0.0.1:8000/test/?format=admin
- http://127.0.0.1:8000/test.admin
- http://127.0.0.1:8000/test/
form表單方式:HTMLFormRenderer
訪問URL:
- http://127.0.0.1:8000/test/?format=form
- http://127.0.0.1:8000/test.form
- http://127.0.0.1:8000/test/
三 局部使用
from rest_framework.renderers import HTMLFormRenderer,BrowsableAPIRenderer class BookDetailView(APIView): renderer_classes = [HTMLFormRenderer,BrowsableAPIRenderer ] def get(self,request,pk): book_obj=models.Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False)return Response(bs.data) def put(self,request,pk): book_obj = models.Book.objects.filter(pk=pk).first() bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): models.Book.objects.filter(pk=pk).delete() return Response("")
四 全局使用
settings裏配置:
REST_FRAMEWORK = { ‘DEFAULT_RENDERER_CLASSES‘:[‘rest_framework.renderers.JSONRenderer‘] }
rest-framework之響應器(渲染器)