将文件从 s3 Bucket 下载到 USERS 计算机

Downloading a file from an s3 Bucket to the USERS computer

目标

将文件从 s3 Bucket 下载到用户计算机。

上下文

我正在为 React 应用开发 Python/Flask API。当用户单击前端的下载按钮时,我想将相应的文件下载到他们的机器上。

我试过的

import boto3 s3 = boto3.resource('s3') s3.Bucket('mybucket').download_file('hello.txt', '/tmp/hello.txt')

我目前正在使用一些代码来查找下载文件夹的路径,然后将该路径作为第二个参数插入到 download_file() 中,连同他们尝试下载的存储桶中的文件.

这在本地工作,并且测试 运行 很好,但我 运行 在部署后遇到了问题。该代码将找到服务器的下载路径,并在那里下载文件。

问题

解决这个问题的最佳方法是什么?我已经研究过,但找不到能够将文件从 s3 存储桶下载到用户下载文件夹的好的解决方案。非常感谢任何 help/advice。

您应该不需要将文件保存到服务器。您可以将文件下载到内存中,然后构建一个包含该文件的 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)

这对于小文件来说没问题,用户不会有任何有意义的等待时间。但是对于较大的文件,这会影响用户体验。该文件将需要完全下载到服务器,然后再下载给用户。因此,要解决此问题,请使用 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 文件进行了测试。

解决这个问题的更好方法是 create presigned url。这为您提供了一个临时的 URL,它在一定时间内有效。它还删除了您的烧瓶服务器作为 AWS s3 存储桶之间的代理,从而减少了用户的下载时间。

def get_attachment_url():
   bucket = 'BUCKET_NAME'
   key = 'FILE_KEY'

   client: boto3.s3 = boto3.client(
     's3',
     aws_access_key_id=YOUR_AWS_ACCESS_KEY,
     aws_secret_access_key=YOUR_AWS_SECRET_KEY
   )

   return client.generate_presigned_url('get_object',
                                     Params={'Bucket': bucket, 'Key': key},
                                     ExpiresIn=60) `