将存储在 S3 上的文件流式传输到客户端,而无需将其下载到 Flask 服务器

Stream files stored on S3 to client without downloading it to flask server

我有一个与 S3 通信的服务器,我想将 mp3 文件提供给客户端的浏览器而不将它们下载到服务器。这些文件需要经过身份验证的用户才能访问它们,因此它们都是私有的。 我也不确定这种功能是专门位于服务器代码上还是可以通过某些 JS 来完成。 我的问题是什么是正确的方法以及如何做?

我的烧瓶代码基本上是这样工作的:

@app.route('/audio')
def audio():

    s3 = boto_session.client("s3", region_name='us-west-2')
    file_name = 'some_file_on_s3'
    download_path = './static/' + file_name
    bucket_name = 'some_bucket'
    s3.download_file(bucket_name, file_name, download_path)

    return render_template('audio.html', file_source=file_name) 

我的 'audio.html' 文件如下所示:

<!DOCTYPE html>
<html lang="en">

<head>
</head>

<body>
    <audio id="t-rex-roar" controls src="{{'./static/'+file_source}}">
    Your browser does not support the
    <code>audio</code> element.
    </audio>
</body>
</html>

您应该 return 客户端应用程序使用 S3 file sharing mechanisms 直接 link 到 S3 文件。通过 Flask 代理 S3 文件是非常缓慢且总体上很糟糕的方法。