Skip to content

Commit

Permalink
views.download_csv_file to use DefaultStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
nucleogenesis committed Jan 14, 2025
1 parent c7c169c commit ebc6d37
Showing 1 changed file with 12 additions and 15 deletions.
27 changes: 12 additions & 15 deletions kolibri/plugins/facility/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import io
import json
import os
from datetime import datetime as dt

from django.core.exceptions import PermissionDenied
from django.core.files.storage import DefaultStorage
from django.http import Http404
from django.http import HttpResponse
from django.http.response import FileResponse
Expand Down Expand Up @@ -187,34 +187,31 @@ def download_csv_file(request, csv_type, facility_id):
).replace("-", "_"),
}

file_storage = DefaultStorage()

if csv_type in CSV_EXPORT_FILENAMES.keys():
if csv_type == "user":
filepath = os.path.join(
conf.KOLIBRI_HOME,
"log_export",
CSV_EXPORT_FILENAMES[csv_type].format(facility.name, facility.id[:4]),
filename = CSV_EXPORT_FILENAMES[csv_type].format(
facility.name, facility.id[:4]
)
else:
log_request = _get_log_request(csv_type, facility_id)
if log_request:
start = log_request.selected_start_date.isoformat()
end = log_request.selected_end_date.isoformat()
filepath = os.path.join(
conf.KOLIBRI_HOME,
"log_export",
CSV_EXPORT_FILENAMES[csv_type].format(
facility.name, facility.id[:4], start[:10], end[:10]
),

filename = CSV_EXPORT_FILENAMES[csv_type].format(
facility.name, facility.id[:4], start[:10], end[:10]
)
else:
filepath = None
filename = None

# if the file does not exist on disk, return a 404
if filepath is None or not os.path.exists(filepath):
if not file_storage.exists(filename):
raise Http404("There is no csv export file for {} available".format(csv_type))

# generate a file response
response = FileResponse(io.open(filepath, "rb"))
response = FileResponse(file_storage.open(filename, "rb"))
# set the content-type by guessing from the filename
response.headers["Content-Type"] = "text/csv"

Expand All @@ -234,6 +231,6 @@ def download_csv_file(request, csv_type, facility_id):
translation.deactivate()

# set the content-length to the file size
response.headers["Content-Length"] = os.path.getsize(filepath)
response.headers["Content-Length"] = file_storage.size(filename)

return response

0 comments on commit ebc6d37

Please sign in to comment.