Estoy intentando descargarme un zip con archivos extraidos de S3 Amazon en Python pero me da error.
El código sería este:
for id_file in files:
chargeFile=ChargeFiles.objects.get(id=id_file)
...
s3 = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY_ID,aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,region_name='eu-west-2')
s3_response_object['Body'] = s3_response_object['Body'].read().decode("ISO-8859-1")
s3_response_object['Key'] = settings.AWS_ACCESS_KEY_ID+'/'+settings.AWS_SECRET_ACCESS_KEY
location = s3.get_bucket_location(Bucket=BUCKET_NAME)['LocationConstraint']
url = "https://s3-%s.amazonaws.com/%s/%s" % (location, BUCKET_NAME, BUCKET_FILE_NAME)
s3_response_object['URL'] = url
s3_response_object=s3.get_object(Bucket=BUCKET_NAME,Key=BUCKET_FILE_NAME)
...
//LA DESCARGA DEL ARCHIVO LA HACE CORRECTA
resultFiles.append(s3_response_object)
full_zip_in_memory = generate_zip(resultFiles)
response = HttpResponse(full_zip_in_memory, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'documentacion_incidencias.zip'
return response
Y la función generate_zip es la siguiente:
def generate_zip(files):
mem_zip = BytesIO()
with zipfile.ZipFile(mem_zip, mode="w",compression=zipfile.ZIP_DEFLATED) as zf:
for f in files:
zf.writestr(f[0], f[1])
return mem_zip.getvalue()
Me devuelve error con un 0 simplemente, en la fila zf.writestr(f[0], f[1])
KeyError at /incidents/
0
Request Method: POST
Request URL: http://127.0.0.1:8000/incidents/
Django Version: 2.2.1
Exception Type: KeyError
Exception Value:
0
Exception Location: truckers/viewsAjax.py in generate_zip, line 1667
Python Executable: /usr/bin/python3
Python Version: 3.6.9
Python Path:
[---]
Server time: Vie, 23 Abr 2021 08:38:34 +0200
Traceback Switch to copy-and-paste view
/home/miguel/.local/lib/python3.6/site-
packages/django/core/handlers/exception.py in inner
response = get_response(request) …
▶ Local vars
/home/miguel/.local/lib/python3.6/site-
packages/django/core/handlers/base.py in _get_response
response = self.process_exception_by_middleware(e,
request) …
▶ Local vars
/home/miguel/.local/lib/python3.6/site-
packages/django/core/handlers/base.py in _get_response
response = wrapped_callback(request, *callback_args,
**callback_kwargs) …
▶ Local vars
/home/.local/lib/python3.6/site-
packages/django/contrib/auth/decorators.py in _wrapped_view
return view_func(request, *args, **kwargs) …
▶ Local vars /incidents/views.py in showIncidents
full_zip_in_memory = generate_zip(resultFiles) …
▶ Local vars incidents/views.py in generate_zip
zf.writestr(f[0], f[1])
¿Como puedo coger corréctamente el objeto que devuelve Amazon? ¿O Es correcta la función?
Gracias.