How do I use django rest framework to send a file in response?

前端 未结 4 714
北恋
北恋 2021-02-15 18:27

I need to send a pdf file and some other parameters in response to a get API call using django rest framework.

How can I do it? I tried this but it gives an error

4条回答
  •  野性不改
    2021-02-15 18:36

    You can use DRF-PDF project with PDFFileResponse:

    from rest_framework import status
    from rest_framework.views import APIView
    from drf_pdf.response import PDFFileResponse
    from drf_pdf.renderer import PDFRenderer
    
    
    class PDFHandler(APIView):
    
        renderer_classes = (PDFRenderer, )
    
        def get(self, request):
            return PDFFileResponse(
                file_path='/path/to/file.pdf',
                status=status.HTTP_200_OK
            )
    

    But, maybe you cannot respond in both formats (json and stream).

提交回复
热议问题