Error when displaying contents of a .csv in Django (backend in S3 AWS)
I'm having quite a trouble when displaying in JSON format the contents of a .csv file located in a S3 Bucket. I am able to do the GET method correctly, but I think that I'm doing something wrong when trying to display the contents of the previously mentioned file.
Also I get this error: TemplateSyntaxError at /flightlogs Could not parse the remainder: '[file]' from 'csv_contents[file]'. Probably due to bad code of the django html, but I don't know what else I can do.
Current Python code is:
def flightlogs(request):
# configure boto3, this works
csv_files = []
try:
response = s3_client.list_objects_v2(Bucket=bucket_name)
for obj in response.get('Contents', []):
if obj['Key'].endswith('.csv'):
csv_files.append(obj['Key'])
except Exception as e:
print(f"Error al listar archivos en el bucket: {e}")
# this is for saving the content of the .csv
csv_contents = {}
# Itera sobre cada archivo CSV encontrado
for file_key in csv_files:
try:
# Obtiene el objeto (archivo) desde S3
obj = s3_client.get_object(Bucket=bucket_name, Key=file_key)
# Lee el contenido del archivo y lo decodifica como UTF-8
content = obj['Body'].read().decode('utf-8')
# Lee el contenido CSV y lo convierte en una lista de diccionarios
csv_reader = csv.DictReader(StringIO(content))
rows = list(csv_reader)
# Convierte la lista de diccionarios a JSON con formato indentado
csv_contents[file_key] = json.dumps(rows, indent=4)
except Exception as e:
# Manejo de errores en caso de problemas al leer un archivo CSV
print(f"Error al leer el archivo {file_key}: {e}")
csv_contents[file_key] = f"Error al leer el archivo: {e}"
# Renderiza el HTML con la lista de archivos y sus contenidos
return render(request, 'flight_logs_landing.html', {'csv_files': csv_files, 'csv_contents': csv_contents})
And current HTML code is:
{% extends "base.html" %}
{% load static %}
{% block content %}
<section class="section-sm" style="min-height: 100vh">
<div class="container">
<h1 class="mx-auto my-3 w-50 text-center">SAETA Flight Logs</h1>
<ul class="list-group">
{% for content in csv_contents %}
<li class="list-group-item">
<h2>{{ file }}</h2>
<pre>{{ csv_contents[file] }}</pre>
</li>
{% empty %}
<li class="list-group-item">No hay archivos CSV disponibles.</li>
{% endfor %}
</ul>
</div>
</section>
{% endblock %}