Skip to content

Instantly share code, notes, and snippets.

@jacoduplessis
Last active March 28, 2019 05:45
Show Gist options
  • Save jacoduplessis/33674d9a6f636705a18256644b4d71a6 to your computer and use it in GitHub Desktop.
Save jacoduplessis/33674d9a6f636705a18256644b4d71a6 to your computer and use it in GitHub Desktop.
Stream SQLAlchemy result as CSV response in Django
import csv
from sqlalchemy.engine.result import ResultProxy
class _Echo:
def write(self, value):
return value
def stream_csv(res: ResultProxy):
w = _Echo()
writer = csv.writer(w)
yield writer.writerow(res.keys())
for row in res:
yield writer.writerow(row)
from django.http.response import StreamingHttpResponse
from .utils import stream_csv
class StreamCSVView(generic.View):
def get(self, request, pk):
sql = """select count(*) from table"""
res = connection_or_engine.execute(text(sql))
return StreamingHttpResponse(stream_csv(res), content_type='text/csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment