Skip to content

Instantly share code, notes, and snippets.

@chrisforrette
Created November 13, 2015 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisforrette/415d04b1b6edbce9d813 to your computer and use it in GitHub Desktop.
Save chrisforrette/415d04b1b6edbce9d813 to your computer and use it in GitHub Desktop.
import csv
from django.http import HttpResponse
def serve_report(filename, fieldnames, data):
"""
Generate a CSV with the passed in `fieldnames` and `data`
and return a response with it as an attachment as `filename` + .csv
"""
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="%s.csv"' % filename
writer = csv.DictWriter(response, fieldnames=fieldnames)
writer.writeheader()
if len(data):
writer.writerows(data)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment