使用Django从Amazon S3下载文件

Moh*_*rki 8 django amazon-s3

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

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
Run Code Online (Sandbox Code Playgroud)

var*_*tec 9

如果您不希望文件可下载,请将ACL设置为私有(仅可通过您的帐户访问).您的用户仍然可以下载文件,您是否为他们提供了签名URL.签署URL时,会生成具有过期时间的令牌.您可以将其设置为合理的10分钟.使用适用于Python的Amazon Web Services界面 - 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)
Run Code Online (Sandbox Code Playgroud)

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


so_*_*so_ 8

我无法轻易找到指定如何执行此操作的任何地方,并在我搜索时再次回到此问题.所以

使用boto后端的django-storages,这样做的方法就像

filepath = settings.MEDIA_DIRECTORY + file.name
response_headers = {
    'response-content-type': 'application/force-download',
    'response-content-disposition':'attachment;filename="%s"'%file.name
    }
url = s3.generate_url(60, 'GET',
                bucket=settings.AWS_STORAGE_BUCKET_NAME,
                key=filepath,
                response_headers=response_headers,
                force_http=True)
return http.HttpResponseRedirect(url)
Run Code Online (Sandbox Code Playgroud)

  • 我发现这是目前内置于django-storages的.按照上面的例子,这可以完成:`url = storage.url(filepath,headers = response_headers)` (3认同)

小智 5

上面的答案已经过时了,因为他们使用 boto 而不是 boto3。boto3 的实现方式如下:

import boto3

client = boto3.client('s3', aws_access_key_id = config('AWS_ACCESS_KEY_ID'), /
aws_secret_access_key = config('AWS_SECRET_ACCESS_KEY'))
bucket_name = config('AWS_STORAGE_BUCKET_NAME')
file_name = settings.AWS_MEDIA_LOCATION + '/' + 'file-name'

url = client.generate_presigned_url(
                                    'get_object', 
                                    Params = { 
                                                'Bucket': bucket_name, 
                                                'Key': file_name, }, 
                                    ExpiresIn = 600, )
return HttpResponseRedirect(url)
Run Code Online (Sandbox Code Playgroud)