【问题标题】:Download multiple files from S3 django从 S3 django 下载多个文件
【发布时间】:2017-04-14 00:45:18
【问题描述】:

这是我使用的链接 (Download files from Amazon S3 with Django)。使用它我可以下载单个文件。

代码:

s3_template_path = queryset.values('file')
filename = 'test.pdf'
conn = boto.connect_s3('<aws access key>', '<aws secret key>')
bucket = conn.get_bucket('your_bucket')
s3_file_path = bucket.get_key(s3_template_path)
response_headers = {
'response-content-type': 'application/force-download',
'response-content-disposition':'attachment;filename="%s"'% filename
}
url = s3_file_path.generate_url(60, 'GET',
            response_headers=response_headers,
            force_http=True)
return HttpResponseRedirect(url)

我需要从 S3 下载多个文件,因为 zip 会更好。是否可以修改和使用上述方法。如果不是,请建议其他方法。

【问题讨论】:

  • 您要查找的每个文件的 s3_template_path 是否相同?
  • 不,模板路径不同

标签: python django amazon-web-services amazon-s3


【解决方案1】:

好的,这是一个可能的解决方案,它基本上是下载每个文件并将它们压缩到一个文件夹中,然后将其返回给用户。

不确定每个文件的s3_template_path 是否相同,但如有必要,请更改此设置

# python 3

import requests
import os
import zipfile

file_names = ['test.pdf', 'test2.pdf', 'test3.pdf']

# set up zip folder
zip_subdir = "download_folder"
zip_filename = zip_subdir + ".zip"
byte_stream = io.BytesIO()
zf = zipfile.ZipFile(byte_stream, "w")  


for filename in file_names:
    s3_template_path = queryset.values('file')  
    conn = boto.connect_s3('<aws access key>', '<aws secret key>')
    bucket = conn.get_bucket('your_bucket')
    s3_file_path = bucket.get_key(s3_template_path)
    response_headers = {
    'response-content-type': 'application/force-download',
    'response-content-disposition':'attachment;filename="%s"'% filename
    }
    url = s3_file_path.generate_url(60, 'GET',
                response_headers=response_headers,
                force_http=True)

    # download the file
    file_response = requests.get(url)  

    if file_response.status_code == 200:

        # create a copy of the file
        f1 = open(filename , 'wb')
        f1.write(file_response.content)
        f1.close()

        # write the file to the zip folder
        fdir, fname = os.path.split(filename)
        zip_path = os.path.join(zip_subdir, fname)
        zf.write(filename, zip_path)    

    # close the zip folder and return
    zf.close()
    response = HttpResponse(byte_stream.getvalue(), content_type="application/x-zip-compressed")
    response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
    return response        

【讨论】:

  • 对不起我编辑了两次,这个版本应该可以工作,只要file_response = requests.get(url)正确返回文件
  • 谢谢,试试这个
  • 好的,你可能需要在循环中生成 s3_template_path,如果它有效,请告诉我
  • 您好,我尝试使用此代码,但我收到了这种错误 'str' object has no attribute 'get' 。 .顺便说一句,我正在使用 django 2.2 和 python 3..
猜你喜欢
  • 1970-01-01
  • 2012-10-10
  • 2013-05-08
  • 2010-10-02
  • 2017-03-29
  • 1970-01-01
  • 2022-06-16
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多