From 435d075eead1ea1d172e05bdc659fdbc76462b9e Mon Sep 17 00:00:00 2001 From: Mark Brough Date: Sun, 20 Nov 2022 16:50:14 +0100 Subject: [PATCH 1/3] Add CSV response for facts endpoint --- babbage/api.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/babbage/api.py b/babbage/api.py index d75c7fb..a159422 100644 --- a/babbage/api.py +++ b/babbage/api.py @@ -170,6 +170,9 @@ def facts(name): page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' + + if request.args.get('format', '').lower() == 'csv': + return create_csv_response(result['data']) return jsonify(result) From aa8e70159dbef4c3b5df54f4e77417827b60f33a Mon Sep 17 00:00:00 2001 From: Mark Brough Date: Sun, 20 Nov 2022 16:50:35 +0100 Subject: [PATCH 2/3] Add CSV response for members endpoint --- babbage/api.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/babbage/api.py b/babbage/api.py index a159422..ef23042 100644 --- a/babbage/api.py +++ b/babbage/api.py @@ -186,4 +186,7 @@ def members(name, ref): page=request.args.get('page'), page_size=request.args.get('pagesize')) result['status'] = 'ok' + + if request.args.get('format', '').lower() == 'csv': + return create_csv_response(result['data']) return jsonify(result) From 80820f2c9927de1680264079cfe2f23348466752 Mon Sep 17 00:00:00 2001 From: Mark Brough Date: Sun, 20 Nov 2022 17:27:46 +0100 Subject: [PATCH 3/3] Fix CSV output by using csv.writer --- babbage/api.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/babbage/api.py b/babbage/api.py index ef23042..59051a9 100644 --- a/babbage/api.py +++ b/babbage/api.py @@ -2,6 +2,8 @@ # TODO: consider making this it's own Python package? from datetime import date from decimal import Decimal +import csv +import io from werkzeug.exceptions import NotFound from flask import Blueprint, Response, request, current_app, json, url_for @@ -66,19 +68,24 @@ def jsonify(obj, status=200, headers=None): def create_csv_response(rows): def _generator(): + output = io.StringIO() + csvwriter = csv.writer(output) convert_to_str = lambda value: str(value) if value is not None else '' # noqa columns = [] for index, row in enumerate(rows): if index == 0: columns = sorted(row.keys()) - yield ','.join(columns) + '\n' - + csvwriter.writerow(columns) data = [ convert_to_str(row.get(column)) for column in columns ] - yield ','.join(data) + '\n' + csvwriter.writerow(data) + output.seek(0) + yield output.read() + output.truncate(0) + output.seek(0) return Response( _generator(),