Aquí está el enlace que he usado ( Descargar archivos de Amazon S3 con Django ). Usando esto, puedo descargar un solo archivo.
Código:
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)
Necesito descargar varios archivos de S3, ya que un zip sería mejor. ¿Se puede modificar y utilizar el método mencionado? Si no es así, sugiera otro método.
De acuerdo, aquí hay una posible solución, básicamente descarga cada archivo y los comprime en una carpeta, luego se lo devuelve al usuario.
No estoy seguro si s3_template_path
es el mismo para cada archivo, pero cámbielo si es necesario
# 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