可以用Flask把文件一个一个发给客户端吗?
Can I send files one by one to the client with Flask?
假设我有很多图像,循环浏览它们需要 1 小时。我想向客户发送适合条件的图像。我不想同时发送所有这些,因为客户端必须等待 1 小时才能获取图像。我想一次发送一张图片,只要每张图片都通过条件。
下面的代码不会向客户端发送任何文件,因为 send_file
创建的对象需要 returned。当然,如果我return对象,只会发送第一个文件。
@app.route('/img_process', methods=['POST'])
def img_process():
for file in files:
if condition:
send_file(photo_path, mimetype='image/jpg')
我能找到的唯一解决方案是使用网络套接字,例如 Socket.IO。
操作方法如下:
- 在前端设置监听器:
// Socket listener for the "receive_image" event
socket.on('receive_image', (image) => {
// Here you set the "src" of an image tag to be `image` (which is a string)
});
// Make a request to "img_process"
axios.post('http://127.0.0.1:5000/img_process');
- 在后端设置发射器:
@app.route('/img_process', methods=['POST'])
def img_process():
for file in files:
if condition:
# Load the image with OpenCV and convert it into text
photo = cv2.imread('path/to/image')
_, photo = cv2.imencode('.jpg', photo) # Change "jpg" to your file format of choice
text_photo = base64.b64encode(photo).decode('utf-8')
# Emit the image to the "receive_image" event which was set up in the front end.
# Change "jpg" to the file format you chose.
socketio.emit('receive_image', 'data:image/jpg;base64,' + text_photo)
灵感来自 https://gist.github.com/companje/b95e735650f1cd2e2a41 :)
假设我有很多图像,循环浏览它们需要 1 小时。我想向客户发送适合条件的图像。我不想同时发送所有这些,因为客户端必须等待 1 小时才能获取图像。我想一次发送一张图片,只要每张图片都通过条件。
下面的代码不会向客户端发送任何文件,因为 send_file
创建的对象需要 returned。当然,如果我return对象,只会发送第一个文件。
@app.route('/img_process', methods=['POST'])
def img_process():
for file in files:
if condition:
send_file(photo_path, mimetype='image/jpg')
我能找到的唯一解决方案是使用网络套接字,例如 Socket.IO。
操作方法如下:
- 在前端设置监听器:
// Socket listener for the "receive_image" event
socket.on('receive_image', (image) => {
// Here you set the "src" of an image tag to be `image` (which is a string)
});
// Make a request to "img_process"
axios.post('http://127.0.0.1:5000/img_process');
- 在后端设置发射器:
@app.route('/img_process', methods=['POST'])
def img_process():
for file in files:
if condition:
# Load the image with OpenCV and convert it into text
photo = cv2.imread('path/to/image')
_, photo = cv2.imencode('.jpg', photo) # Change "jpg" to your file format of choice
text_photo = base64.b64encode(photo).decode('utf-8')
# Emit the image to the "receive_image" event which was set up in the front end.
# Change "jpg" to the file format you chose.
socketio.emit('receive_image', 'data:image/jpg;base64,' + text_photo)
灵感来自 https://gist.github.com/companje/b95e735650f1cd2e2a41 :)