Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CSV response #38

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions babbage/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -170,6 +177,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)


Expand All @@ -183,4 +193,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)