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

>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.

Leave a Reply