[Python] How can I stream a large CSV download in Flask without loading the whole file into...

Discussão em 'Python' iniciado por Stack, Maio 14, 2025.

  1. Stack

    Stack Membro Participativo

    I have an endpoint that exports the report as a CSV.

    import io, csv
    from flask import Flask, Response

    app = Flask(__name__)

    def get_report_rows():
    # imagine 5 million DB rows here
    for i in range(5_000_000):
    yield (i, f"name-{i}", i % 100)

    @app.get("/export")
    def export():
    rows = get_report_rows()

    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(["id", "name", "score"])
    writer.writerows(rows)
    output.seek(0)

    return Response(
    output.getvalue(),
    mimetype="text/csv",
    headers={"Content-Disposition": "attachment; filename=report.csv"}
    )



    For large datasets, this endpoint crashes. How can I create the endpoint such that I can stream a CSV row by row?

    Continue reading...

Compartilhe esta Página