目标
将文件从s3存储桶下载到用户计算机。
上下文
我正在为一个React应用开发Python/Flask API。当用户单击前端上的Download按钮时,我希望将适当的文件下载到他们的计算机上。
我尝试过的
import boto3 s3 = boto3.resource('s3') s3.Bucket('mybucket').download_file('hello.txt', '/tmp/hello.txt')
我目前正在使用一些代码来查找downloads文件夹的路径,然后将该路径作为第二个参数插入到download_file()中,以及他们试图下载的存储桶上的文件。
这在本地工作,测试运行得很好,但一旦部署,我就遇到了问题。代码将找到服务器的下载路径,并将文件下载到那里。
问题
实现这一目标的最好方法是什么?我已经研究过,但找不到一个好的解决方案,可以将文件从s3存储桶下载到users downloads文件夹。任何帮助/建议都是非常感谢的。
发布于 2017-04-05 06:26:04
您不需要将文件保存到服务器。您可以将该文件下载到内存中,然后构建一个包含该文件的Response
对象。
from flask import Flask, Response
from boto3 import client
app = Flask(__name__)
def get_client():
return client(
's3',
'us-east-1',
aws_access_key_id='id',
aws_secret_access_key='key'
)
@app.route('/blah', methods=['GET'])
def index():
s3 = get_client()
file = s3.get_object(Bucket='blah-test1', Key='blah.txt')
return Response(
file['Body'].read(),
mimetype='text/plain',
headers={"Content-Disposition": "attachment;filename=test.txt"}
)
app.run(debug=True, port=8800)
这对于小文件来说是可以的,用户不会有任何有意义的等待时间。然而,对于较大的文件,这将影响UX。该文件需要完全下载到服务器,然后再下载给用户。因此,要解决此问题,请使用get_object
方法的Range
关键字参数:
from flask import Flask, Response
from boto3 import client
app = Flask(__name__)
def get_client():
return client(
's3',
'us-east-1',
aws_access_key_id='id',
aws_secret_access_key='key'
)
def get_total_bytes(s3):
result = s3.list_objects(Bucket='blah-test1')
for item in result['Contents']:
if item['Key'] == 'blah.txt':
return item['Size']
def get_object(s3, total_bytes):
if total_bytes > 1000000:
return get_object_range(s3, total_bytes)
return s3.get_object(Bucket='blah-test1', Key='blah.txt')['Body'].read()
def get_object_range(s3, total_bytes):
offset = 0
while total_bytes > 0:
end = offset + 999999 if total_bytes > 1000000 else ""
total_bytes -= 1000000
byte_range = 'bytes={offset}-{end}'.format(offset=offset, end=end)
offset = end + 1 if not isinstance(end, str) else None
yield s3.get_object(Bucket='blah-test1', Key='blah.txt', Range=byte_range)['Body'].read()
@app.route('/blah', methods=['GET'])
def index():
s3 = get_client()
total_bytes = get_total_bytes(s3)
return Response(
get_object(s3, total_bytes),
mimetype='text/plain',
headers={"Content-Disposition": "attachment;filename=test.txt"}
)
app.run(debug=True, port=8800)
这将以1MB块为单位下载文件,并在下载时将其发送给用户。这两种方法都已经用一个40MB的.txt
文件进行了测试。
https://stackoverflow.com/questions/43215889
复制相似问题