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

前端 未结 4 700
北恋
北恋 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:55

    The problem here is that you are trying to return a mix of JSON and PDF, which either isn't what you are looking for or is going to return a giant base64-encoded response. PDF is a binary format and JSON is a text format, and you can't really mix them well.

    Within a DRF view you can directly return a Django response, which you already appear to be generating (the HttpResponse), and DRF will pass it through and skip the renderers. This is useful in cases like this, as it allows you to return a binary response such as an image or PDF without worrying about DRF's rendering layer causing problems.

    @detail_route(methods=['get'])
    def fetch_report(self, request, *args, **kwargs):
        short_report = open("somePdfFile", 'rb')
        response = HttpResponse(FileWrapper(short_report), content_type='application/pdf')
        return response
    

    The alternative is to encode the PDF as text, using something like base64 encoding. This will dramatically increase your response sizes, but it will allow you to use DRF's rendering layer without problems.

    @detail_route(methods=['get'])
    def fetch_report(self, request, *args, **kwargs):
        import base64
        short_report = open("somePdfFile", 'rb')
        report_encoded = base64.b64encode(short_report.read())
        return Response({'detail': 'this works',
            'report': report_encoded})
    

    But the route I would recommend here is to generate the PDF and store it in either your media storage, or an alternative private location, and provide a direct link to it in your response. This way you don't need to worry about the encoding issues, don't need to directly return the PDF, and don't need to worry about directly serving the PDF.

提交回复
热议问题