I have a Python Flask app that gets request to download a file from a remote FTP server. I have used BytesIO
to save contents of the file downloaded from FTP server using retrbinary
:
import os
from flask import Flask, request, send_file
from ftplib import FTP
from io import BytesIO
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/download_content', methods=['GET'])
def download_content():
filepath = request.args.get("filepath").strip()
f = FTP(my_server)
f.login(my_username, my_password)
b = BytesIO()
f.retrbinary("RETR " + filepath, b.write)
b.seek(0)
return send_file(b, attachment_filename=os.path.basename(filepath))
app.run("localhost", port=8080)
The issue here is that when the download_content
route is hit, first the contents of the file comes in the BytesIO
object, then it is sent to the frontend for downloading.
How can I stream the file to frontend while it is being downloading from FTP server? I can't wait for the file to get downloaded entirely in BytesIO
object and then do a send_file
, as that could be both, memory inefficient as well as more time consuming.
I have read that Flask's send_file
accepts a generator
object, but how can I make the BytesIO
object yield
to send_file
in chunks?