-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·48 lines (40 loc) · 1.2 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/env python
# Flask
import os
import urllib2
from flask import request
from flask import Flask
from flask import Response
# json to csv
from StringIO import StringIO
from json import load
from urllib import urlopen
from urllib import urlencode
import csv
app = Flask(__name__)
@app.route('/')
def json2csv():
sql = request.args.get('q')
if sql == None:
status = 400
response = 'You must send a ?q= parameter.'
else:
url = 'https://premium.scraperwiki.com/cc7znvq/47d80ae900e04f2/sql/'
query_string = urlencode({'q':sql})
handle = urlopen(url + '?' + query_string)
if handle.code == 200:
data = load(handle)
s = StringIO()
w = csv.DictWriter(s, data[0].keys())
w.writeheader()
w.writerows(data)
status = 200
response = s.getvalue()
else:
status = handle.code
response = handle.read()
return Response(response=response, status=status, content_type='application/json')
if __name__ == '__main__':
# Bind to PORT if defined, otherwise default to 5000.
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)