Skip to content

Instantly share code, notes, and snippets.

@danjac
Created June 14, 2024 12:15
Show Gist options
  • Save danjac/31c025445a51bd90754ca47d1d718d37 to your computer and use it in GitHub Desktop.
Save danjac/31c025445a51bd90754ca47d1d718d37 to your computer and use it in GitHub Desktop.
Django CSV download using StreamingHttpResponse
import csv
class CSVBuffer:
"""Handles CSV output."""
def write(self, value):
"""Handles file-like write, just returning the value"""
return value
def download_csv(request):
"""Returns a CSV download of something"""
# will write to our buffer, which returns each row to streaming response
writer = csv.writer(CSVBuffer())
response = StreamingHttpResponse(
write_rows(writer), content_type="text/csv"
)
response["Content-Disposition"] = f'attachment; filename=download.csv"'
return response
def write_rows(writer):
"""Generator for writing CSV. Let's assume some sample data that
returns an iterable of dictionaries"""
data = get_sample_data()
if not data:
return # just returns empty generator
# CSV headers, assume there's a function that does this
yield writer.writerow(get_csv_headers(data))
# write each row
for row in data:
yield writer.writerow(row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment