在Elastic Beanstalk上我使用以下Python代码来处理POST请求并将文件上传到S3存储桶。但是,我收到以下错误:
fileobj必须实现读取
在阅读了Flask的FileStorage文档后,我尝试用f.stream代替f,但后来我得到了:
预期的字符串或缓冲区
我正在使用Werkzeug 0.10.1。我该如何解决这个问题?
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from s3upload.helpers import *
application = Flask(__name__)
application.config.from_object('s3upload.config')
ALLOWED_EXTENSIONS = ('pdf','p')
def allowed_file(filename):
if filename.rsplit('.')[1].lower() in ALLOWED_EXTENSIONS:
return True
def upload_file_to_s3(f, bucket_name, acl='public-read'):
try:
s3.upload_fileobj(f, bucket_name, f.filename, ExtraArgs={
"ACL": acl,
"ContentType": f.content_type
})
except Exception as e:
return "Something bad happened while uploading {} in {}: {} {}".format(f.filename, bucket_name, e)
return '{}{}'.format(application.config['S3_LOCATION'], f.filename)
@application.route('/', methods=['POST','GET'])
def upload_file():
if request.method == 'POST':
if 'file' not in request.files:
return "No file key in request.files"
f = request.files['file']
if f.filename == '':
return "Please select a file."
if allowed_file(f.filename):
f.filename = secure_filename(f.filename)
out = upload_file_to_s3(f, application.config['S3_BUCKET'])
return str(out)
else:
return "File type not allowed."
return render_template('index.html')
if __name__ == '__main__':
application.run()