使用 Django 从 Amazon S3 下载文件 [英] Download files from Amazon S3 with Django

查看:37
本文介绍了使用 Django 从 Amazon S3 下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Django 应用程序,允许用户下载他们购买的 MP3 文件,这些 MP3 文件托管在 Amazon S3 中.当用户点击下载"按钮而不允许他们看到原始链接(到亚马逊)时,如何强制下载?我有一个下载文件的视图,但文件已损坏.这是它的样子:

I have a Django app that allows users to download MP3 files that they purchased and these MP3 files are hosted in Amazon S3. How can I force a download when users click a "download" button without allowing them to see the original link (to Amazon)? I have a view that downloads the file but the file is corrupt. Here is how it looks like:

def download(request):
    filename = 'https://s3-eu-west-1.amazonaws.com/skempi/Ihsahn/04-emancipation-qtxmp3.mp3'
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition']='attachment;filename="%s"'%filename
    response["X-Sendfile"] = filename
    return response

推荐答案

如果您不希望文件可下载,请将 ACL 设置为私有(只能通过您的帐户访问).如果您向他们提供签名 URL,您的用户仍然可以下载文件.当您签署 URL 时,您会生成带有过期时间的令牌.您可以将其设置为合理的 10 分钟.使用 Amazon Web Services 接口 Python —博托.

If you don't want the files to be downloadable, set ACL to be private (only accessible via your account). Your users will be still able to download file is you provide them with signed URL. When you sign a URL, you generate token with expire time. You can set it to something reasonable as 10 minutes. Use Amazon Web Services interface for Python — Boto.

import boto
conn = boto.connect_s3('<aws access key>', '<aws secret key>')
bucket = conn.get_bucket('your_bucket')
s3_file_path = bucket.get_key('path/to/file')
url = s3_file_path.generate_url(expires_in=600) # expiry time is in seconds

return HttpResponseRedirect(url)

请注意,这是安全的,因为令牌仅对一种请求方法(默认为 GET)有效且仅对一个文件有效.因此,不存在有人重复使用令牌的风险,例如下载其他文件或操纵给定的文件.

Note, that this is safe, as token is only valid only for one request method (GET by default) and only for one file. So there is no risk of someone reusing the token for example download other files or manipulate the file given.

这篇关于使用 Django 从 Amazon S3 下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆