0

In FastApi the below code is used to stream large files

def iterfile(file_name):  #
        with open(file_name, mode="rb") as file_like:  #
            yield from file_like  #

    return StreamingResponse(iterfile(file_), media_type="application/pdf")

However is I dont have the file saved. I have assigned it as variable of type(class 'bytes') Is there a possible way I could use StreamingResponse with the binary file saved as variable instead of a file.

Sanket Wagh
  • 156
  • 1
  • 14
  • If you don't have an iterator, but actually have the whole content available in a variable in memory already, there is no need to use `StreamingResponse`. `Response` accepts bytes as its content directly: https://fastapi.tiangolo.com/advanced/custom-response/#response - so `return Response(your_bytes_in_memory, mediatype="application/octet-stream")` should do what you want? – MatsLindh Aug 04 '23 at 07:31
  • I did that exactly at first . but does this reduce performance ? I though FileResponse or Streaming Response would be better. – Sanket Wagh Aug 04 '23 at 07:43
  • 1
    `StreamingResponse` is to avoid loading everything into memory - you already have everything in memory, so there is no need to wrap it in a generator. FileResponse is a helpful wrapper to do the same thing as you've shown in your example automagically, i.e. when the file object already is a file on disk. Advice: don't chase performance unless it's actually needed - use a profiler to see if _this_ is actually the issue when you get there. Performance depends on every specific use-case - trading memory usage for cpu usage for bandwidth, etc. So then it becomes: why would it be better? – MatsLindh Aug 04 '23 at 07:46

0 Answers0