Skip to content

Instantly share code, notes, and snippets.

@icron icron/export.py
Last active Mar 23, 2016

Embed
What would you like to do?
Flask-Admin Export CSV
from flask import send_file
from pandas import DataFrame
class MyModelView(ModelView):
@expose('/export')
def export(self):
# Grab parameters from URL
page, sort_idx, sort_desc, search, filters = self._get_list_extra_args()
sort_column = self._get_column_by_idx(sort_idx)
if sort_column is not None:
sort_column = sort_column[0]
# Get count and data
page_size_temp = self.page_size
# unset page size for export
self.page_size = None
# get rows with filters applied
count, data = self.get_list(None, sort_column, sort_desc, search, filters)
self.page_size = page_size_temp # reset pagesize to original value
dicts = [rec.__dict__ for rec in data]
# explicitly set columns, not necessary, however it will be out of order otherwise
df = DataFrame.from_records(dicts, columns=[u'id',u'title'])
# use stringio for temp file
buffer = StringIO.StringIO()
# formatted header
df.to_csv(buffer,encoding='utf-8', header=[u'id',u'Title'])
buffer.seek(0)
filename = "export_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M") + ".csv"
return send_file(buffer, attachment_filename=filename, as_attachment=True, mimetype='text/csv')
<li>
<a id="exportButton" href="{{ request.path ~ 'export?' ~ request.query_string }}">Export CSV</a>
</li>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.