我尝试将图像从Flask应用上传到Amazon S3存储桶。这是我的代码:
def s3upload(image, acl='public-read'):
key = app.config['S3_KEY']
secret = app.config['S3_SECRET']
bucket = app.config['S3_BUCKET']
conn = S3Connection(key, secret)
mybucket = conn.get_bucket(bucket)
r = redis.StrictRedis(connection_pool = pool)
iid = r.incr('image')
now = time.time()
r.zadd('image:created_on', now, iid)
k = Key(mybucket)
k.key = iid
k.set_contents_from_string(image.read())
return iid
@app.route('/', methods = ['GET', 'POST'])
def index():
form = ImageForm(request.form)
print 'CHECKING REQUEST'
if request.method == 'POST' and form.image:
print 'VALID REQUEST'
image = form.image.read()
upload = s3upload(image)
print upload
else:
image = None
r = redis.StrictRedis(connection_pool = pool)
last_ten = r.zrange('image:created_on', 0, 9)
print last_ten
images = []
key = app.config['S3_KEY']
secret = app.config['S3_SECRET']
bucket = app.config['S3_BUCKET']
conn = S3Connection(key, secret)
mybucket = conn.get_bucket(bucket)
for image in last_ten:
images.append(mybucket.get_key(image, validate = False))
return render_template('index.html', form=form, images=images, image=image)
但我在k.set_contents_from_string(image.read())
说'FileField' object has no attribute 'read'
时收到错误。我准备好的所有内容都表明这是将图片上传到S3的正确方法,我发现了一些他们在.read()
对象上调用FileField
的示例,但它运行正常。谢谢你的帮助。
答案 0 :(得分:1)
FileField
个对象具有data
属性:
k.set_contents_from_string(image.data.read())
答案 1 :(得分:0)
怎么样
import os
filestream = form.image.raw_data[0]
filestream.seek(0, os.SEEK_END)
read_data = filestream.tell()
或
read_data = form.image.raw_data[0].read()