Skip to content

Instantly share code, notes, and snippets.

@icron
Last active February 9, 2021 15:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icron/3fe933f5b37b21f73dbc to your computer and use it in GitHub Desktop.
Save icron/3fe933f5b37b21f73dbc to your computer and use it in GitHub Desktop.
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>
@neevai
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