響應模塊

響應模塊

1. 做用

根據用戶請求URL或用戶可接受的類型,篩選出合適的 渲染組件。
用戶請求URL:
http://127.0.0.1:8000/test/?format=json
http://127.0.0.1:8000/test.jsonhtml

2. 內置渲染器

顯示json格式:JSONRendererpython

訪問URL:json

默認顯示格式:BrowsableAPIRenderer(能夠修改它的html文件)api

訪問URL:rest

表格方式:AdminRenderercode

訪問URL:orm

**form表單方式:HTMLFormRenderer**htm

訪問URL:get

3. 局部使用

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("")

4. 全局使用

settings.py中配置it

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': ['rest_framework.renderers.JSONRenderer']
}

5. 自定義顯示模塊

from rest_framework.renderers import TemplateHTMLRenderer
class BookDetailView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    def get(self,request,pk):
        book_obj=models.Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj,many=False)
        return Response(bs.data,template_name='aa.html')
<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>Title</title>
</head>
<body>
{{ title }}
{{ publishDate }}
</body>
</html>
相關文章
相關標籤/搜索