我有一个Flask Web应用程序,该应用程序将图像上传到机器学习模型并以zip文件形式返回预测。为了简单起见,此示例中的代码仅上载图像并以zip格式返回。我还在html中实现了flask-dropzone。
这是执行send_from_directory行时得到的错误代码
"GET /horus/download HTTP/1.1" 0
interface.html
<body>
<h3>Welcome to Horus™ v1.0</h3>
{{ dropzone.create(action=url_for('predict')) }}
<button class="btn waves-effect waves-light btn-large" id="upload">Upload
<i class="material-icons right">send</i>
</button>
{{ dropzone.load_js() }}
{{ dropzone.config(custom_options='addRemoveLinks: true,dictRemoveFileConfirmation:"Are you sure you want to remove this file?" ') }}
</body>
</html>
app.py
import base64
import zipfile
import json
import requests
import os
from flask import Flask, request,jsonify,render_template,url_for,redirect,send_from_directory,current_app,send_file,after_this_request
from werkzeug import secure_filename
from keras.preprocessing import image
from lib.JsonToXML import convert
from flask_dropzone import Dropzone
from flask_cors import CORS, cross_origin
app = Flask(__name__)
CORS(app)
app.config['CORS_HEADERS']='Content-Type'
app.config.update(
DROPZONE_ALLOWED_FILE_CUSTOM = True,
DROPZONE_ALLOWED_FILE_TYPE = '.JPG,.JPEG,.jpg,.jpeg',
DROPZONE_UPLOAD_ON_CLICK = True,
DROPZONE_UPLOAD_MULTIPLE = True,
DROPZONE_DEFAULT_MESSAGE = 'Drop files here to upload or click here to open File Explorer. Allowed file extensions: .jpg, .jpeg'
)
dropzone = Dropzone(app)
@app.route('/horus/predict/v1', methods=['POST','GET'])
def predict():
if request.method == 'POST':
for key,files in request.files.items():
if key.startswith('file'):
print(files)
files.save('output/'+ secure_filename(files.filename))
return redirect(url_for('download'))
else:
return render_template('interface.html')
@app.route('/horus/download',methods=['GET'])
@cross_origin(origin='*')
def download():
uploads = os.path.join(current_app.root_path,'output/')
zfile = zipfile.ZipFile('output/Annotations.zip','w',zipfile.ZIP_DEFLATED)
for xfile in os.listdir(uploads):
if xfile.endswith('.jpg'):
zfile.write('output/'+xfile)
zfile.close()
for files in os.listdir(uploads):
if files.endswith('.zip')==False:
os.remove(uploads+files)
print(files + ' deleted.')
return send_from_directory(uploads,'Annotations.zip',as_attachment=True)
if __name__ == '__main__':
app.run('0.0.0.0',debug=True)
在此之前,我以正常形式测试了API,并且效果很好。我实施了flask-dropzone后,发生了此问题。我也尝试实现flask-cors,但结果是相同的。我目前处于死胡同,不胜感激。