Skip to content

Instantly share code, notes, and snippets.

Last active Feb 9, 2021
What would you like to do?
Flask-Admin Export CSV
from flask import send_file
from pandas import DataFrame
class MyModelView(ModelView):
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'])
filename = "export_" +"%Y_%m_%d_%H_%M") + ".csv"
return send_file(buffer, attachment_filename=filename, as_attachment=True, mimetype='text/csv')
<a id="exportButton" href="{{ request.path ~ 'export?' ~ request.query_string }}">Export CSV</a>
Copy link

neevai commented Mar 5, 2020

2020: Set BaseModelView.can_export = True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment