Add CSV support

This commit is contained in:
Marian Steinbach 2019-07-15 17:51:26 +02:00
parent 8c6ecfc96d
commit 96dd3aa959
2 changed files with 24 additions and 2 deletions

View File

@ -22,6 +22,9 @@ Gibt den Zeitpunkt der letzten Aktualisierung der Spider-Ergebnisse zurück.
Gibt Ergebnisse für alle Sites in einem tabellenfreundlichen Format aus. Gibt Ergebnisse für alle Sites in einem tabellenfreundlichen Format aus.
Wenn per `Accept`-Header der Typ `text/csv` angefordert wird, erfolgt die Ausgabe
im CSV-Format. Ansonsten wird JSON ausgegeben.
```json ```json
[ [
{ {

23
main.py
View File

@ -1,7 +1,9 @@
import collections import collections
import csv
import io
import sys
from datetime import datetime from datetime import datetime
from os import getenv from os import getenv
import sys
from wsgiref import simple_server from wsgiref import simple_server
import falcon import falcon
@ -129,7 +131,23 @@ class TableResults(object):
maxage = 48 * 60 * 60 # two days maxage = 48 * 60 * 60 # two days
resp.cache_control = ["max_age=%d" % maxage] resp.cache_control = ["max_age=%d" % maxage]
resp.media = out if req.accept == 'text/csv':
# return CSV
headers = sorted(out[0].keys())
with io.StringIO(newline='\n') as csvfile:
writer = csv.writer(csvfile, quoting=csv.QUOTE_MINIMAL)
writer.writerow(headers)
for row in out:
o = []
for f in headers:
o.append(str(row[f]))
writer.writerow(o)
resp.body = csvfile.getvalue()
resp.content_type = 'text/csv'
resp.status = falcon.HTTP_200
else:
resp.media = out
class SpiderResultsQuery(object): class SpiderResultsQuery(object):
@ -263,6 +281,7 @@ class Index(object):
handlers = media.Handlers({ handlers = media.Handlers({
'application/json': jsonhandler.JSONHandler(), 'application/json': jsonhandler.JSONHandler(),
'text/csv': media.BaseHandler,
}) })
app = falcon.API() app = falcon.API()