Skip to content

Instantly share code, notes, and snippets.

@chapuzzo
Last active July 14, 2020 11:38
Show Gist options
  • Save chapuzzo/3e32c28a556f2db250b21888f91ddf36 to your computer and use it in GitHub Desktop.
Save chapuzzo/3e32c28a556f2db250b21888f91ddf36 to your computer and use it in GitHub Desktop.
in memory dataframe to binary blob (eg. flask)
from io import BytesIO, StringIO
import pandas as pd
from flask import send_file, Flask
server = Flask(__name__)
@server.route("/download/", defaults=dict(name="file"))
@server.route("/download/<name>")
def send_dataframe_as_csv(name):
df = pd.DataFrame()
proxy = StringIO()
df.to_csv(proxy, index=False)
output = BytesIO()
output.write(proxy.getvalue().encode("utf-8"))
output.seek(0)
proxy.close()
filename = "{}.csv".format(name)
return send_file(output, as_attachment=True, attachment_filename=filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment