Last active
March 28, 2019 05:45
-
-
Save jacoduplessis/33674d9a6f636705a18256644b4d71a6 to your computer and use it in GitHub Desktop.
Stream SQLAlchemy result as CSV response in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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