def csv(): ''' to export tables to `.csv` file ''' form = CSVForm() if form.validate_on_submit(): tabels = [t[0] for t in EXPORT_TABLES] if form.table.data not in tabels: flash('Error: wrong entry, something went wrong', 'danger') return redirect(url_for('core.root')) module = getattr(data, form.table.data, None) csv_path = absolute_path(f'csv_{form.table.data}.csv') delimiter = EXPORT_DELIMETERS[form.delimiter.data] with open(csv_path, 'w+') as csv_file: fields = get_module_columns(module) csv_buffer = DictWriter(csv_file, delimiter=delimiter, fieldnames=fields) rows = [{fields[i]: value for i, value in enumerate(values)} for values in get_module_values(module)] form.headers.data and csv_buffer.writeheader() csv_buffer.writerows(rows) return send_file(csv_path, mimetype='csv', as_attachment=True) return render_template('csvs.html', navbar='#snb3', page_title='Export CSV', form=form)
def test_csv_export_headers_disabled_and_tabs(client): with client.application.app_context(): header = get_module_columns(User) rows = get_module_values(User) response = client.post('/csv', data={ 'table': 'User', 'headers': 0, 'delimiter': 1 }, follow_redirects=True) content = response.data.decode('utf-8').split('\r\n') assert response.status == '200 OK' assert len(content) > len(rows) assert '\t'.join(header) not in content for row in map('\t'.join, rows): assert row == content.pop(0)
def test_csv_export(c): header = get_module_columns(User) rows = get_module_values(User) response = c.post('/csv', data={ 'table': 'User', 'headers': 1, 'delimiter': 0 }, follow_redirects=True) content = response.data.decode('utf-8').split('\r\n') assert response.status == '200 OK' assert len(content) > (len(rows) + 1) assert ','.join(header) == content.pop(0) for row in map(','.join, rows): assert row == content.pop(0)