Merge pull request #6 from netzbegruenung/csv-table

Add CSV support
This commit is contained in:
Marian Steinbach 2019-07-15 20:23:47 +02:00 committed by GitHub
commit dbdb053ac1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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.
Wenn per `Accept`-Header der Typ `text/csv` angefordert wird, erfolgt die Ausgabe
im CSV-Format. Ansonsten wird JSON ausgegeben.
```json
[
{

23
main.py
View File

@ -1,7 +1,9 @@
import collections
import csv
import io
import sys
from datetime import datetime
from os import getenv
import sys
from wsgiref import simple_server
import falcon
@ -129,7 +131,23 @@ class TableResults(object):
maxage = 48 * 60 * 60 # two days
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):
@ -263,6 +281,7 @@ class Index(object):
handlers = media.Handlers({
'application/json': jsonhandler.JSONHandler(),
'text/csv': media.BaseHandler,
})
app = falcon.API()