Last active
February 9, 2021 15:34
-
-
Save icron/3fe933f5b37b21f73dbc to your computer and use it in GitHub Desktop.
Flask-Admin Export CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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
2020: Set
BaseModelView.can_export = True