Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FileResponse with file opened using smart-open

I’m trying to let a user download a file from my webpage. The file is in an S3 bucket I’m accessing using smart-open. The issue I’m having is how to combine that with FileReader. Presently I’m getting a TypeError: "expected str, bytes or os.PathLike object, not Reader". The filetypes will be .txt, .pdf and .doc/.docx

My view:

@api_view(['GET'])
def download_attachment(request, pk):
    session = boto3.Session(aws_access_key_id=AWS_ACCESS_KEY_ID,
                            aws_secret_access_key=AWS_SECRET_ACCESS_KEY)
    obj = Attachment.objects.get(id=pk)
    with smart_opener(f's3://______media/public/{str(obj)}',"rb",transport_params={'client':session.client('s3')}) as attachment:
        response = FileResponse(open(attachment, 'rb'))
    response['Content-Disposition'] = f'attachment; filename={obj.file.name}'
    return response

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

open function expects a filesystem path as the first positional argument to open a file located in your computer’s filesystem. That is why you are getting TypeError. I don’t know what smart_opener() does but if it returns a file-like object this object must be passed to FileResponse directly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading