Skip to content

Instantly share code, notes, and snippets.

@Richard-Mathie
Last active July 12, 2018 11:08
Show Gist options
  • Save Richard-Mathie/ffecf414553f8ca4c56eb5b06e791b6f to your computer and use it in GitHub Desktop.
Save Richard-Mathie/ffecf414553f8ca4c56eb5b06e791b6f to your computer and use it in GitHub Desktop.
Flask FTP Binary Stream
credentials.py
venv/
import os
from flask import Flask, request, Response
from ftplib import FTP
from threading import Thread, Event
from queue import Queue, Empty
from io import BytesIO
from credentials import *
app = Flask(__name__)
class FTPDownloader(object):
def __init__(self, host, user, password, timeout=0.01):
self.ftp = FTP(host)
self.ftp.login(user, password)
self.timeout = timeout
def getBytes(self, filename):
print("getBytes")
self.ftp.retrbinary("RETR {}".format(filename) , self.bytes.put)
self.bytes.join() # wait for all blocks in the queue to be marked as processed
self.finished.set() # mark streaming as finished
def sendBytes(self):
while not self.finished.is_set():
try:
yield self.bytes.get(timeout=self.timeout)
self.bytes.task_done()
except Empty:
self.finished.wait(self.timeout)
self.worker.join()
def download(self, filename):
self.bytes = Queue()
self.finished = Event()
self.worker = Thread(target=self.getBytes, args=(filename,))
self.worker.start()
return self.sendBytes()
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/download_content/<string:filename>', methods=['GET'])
def download_content(filename):
# filename = request.args.get("filename").strip()
ftp = FTPDownloader(my_server, my_username, my_password)
return Response(ftp.download(filename), mimetype="image/jpeg")
app.run("localhost", port=8080, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment