-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
73 lines (59 loc) · 2.39 KB
/
app.py
File metadata and controls
73 lines (59 loc) · 2.39 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import json
from kaha.bootstrap import app, db
from flask import Response, jsonify, request
from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.restful
from pprint import pprint
import markdown2
from kaha.models import KahaResource, KahaResourceType, KahaResourceProperty
from kaha import schemas
def _get_data(district, resource_types=''):
resource_for = request.args.get('for', None)
outformat = request.args.get('format', 'json')
query_filter = KahaResource.query
if (district != 'all'):
query_filter = query_filter.filter(KahaResource.district.ilike("%" + district + "%"))
if (resource_for):
query_filter = query_filter.filter_by(resource_for=resource_for)
if resource_types:
query_filter = query_filter.join(KahaResource.types).filter(KahaResourceType.resource_type.in_(resource_types.split(',')))
datalist = query_filter.all()
serializer = schemas.KahaResourceSchema(many=True)
result = serializer.dump(datalist)
if outformat == 'csv':
def _csv(x):
if isinstance(x, list):
return u'%s' % ':'.join(map(str, x))
return u'%s' % x
def generate():
for i, row in enumerate(result.data):
if i == 0:
yield '"' + '","'.join(row.keys()) + '"\n'
yield '"' + '","'.join(map(_csv, row.values())) + '"\n'
return Response(generate(), mimetype='text/csv')
return json.dumps({'count':query_filter.count(), 'data':result.data})
#return jsonify({'resources':result.data})
@app.route("/")
def hello():
with open(os.path.join('./', 'APIDOC.md')) as doc:
return markdown2.markdown(doc.read())
@app.route("/resources/<district>")
def get_resources(district):
return _get_data(district)
@app.route("/resources/<district>/<resource_types>")
def get_resource_of_types(district, resource_types):
return _get_data(district, resource_types)
@app.route("/resource/<uuid>")
def get_resource(uuid):
data = KahaResource.query.filter_by(uuid=uuid).first()
if data:
serializer = schemas.KahaResourceSchema()
result = serializer.dump(data)
return jsonify((result.data))#; //{'data':result.data}
if __name__ == "__main__":
print "Running app"
_port = 2000
if os.environ['APP_SETTINGS'] == 'kaha.config.ProductionConfig':
_port = 80
app.run(host='0.0.0.0', port=_port)