-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py.j2
165 lines (148 loc) · 4.43 KB
/
app.py.j2
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import argparse
import json
import os
import pyld
import requests
import sqlite3
import yaml
from flask import Flask, jsonify, g, Response, request
from flasgger import Swagger
app = Flask(__name__)
import flask
{% if options.swagger %}
template = {{ options.swagger }}
{% else %}
template = {
"swagger": "2.0",
"info": {
"title": "{{ service.title }}",
"description": "API for X data",
"contact": {
"responsibleOrganization": "x-org",
"responsibleDeveloper": "x-dev",
"email": "[email protected]",
"url": "www.x.org",
},
"termsOfService": "http://x.org/terms",
"version": "0.0.1"
},
"schemes": [
"https",
"http"
]
}
{% endif %}
app.config['SWAGGER'] = {
'title': 'SmartBag API',
'uiversion': 3
}
swagger = Swagger(app, template=template)
{% for db in datasets %}
def _jsonify (obj):
return Response(json.dumps(obj, indent=2), mimetype='application/json')
def get_{{ db.name }}_db():
db = getattr(g, '_{{ db.name }}', None)
if db is None:
db_path = "{{ db.db_path }}"
db_path = os.path.join (os.path.dirname(__file__), db_path)
db = g._{{ db.name }} = sqlite3.connect (db_path)
return db
@app.teardown_appcontext
def close_{{ db.name }}_connection(exception):
db = getattr(g, '_{{ db.name }}', None)
if db is not None:
db.close()
{{ db.name }}_connection = sqlite3.connect ("{{ db.db_path }}")
@app.route('/{{ db.name }}_metadata/')
def {{ db.name }}_metadata ():
""" Get service metadata
---
responses:
200:
description: ...
"""
return _jsonify({{ db.jsonld_context_text }})
@app.route('/{{ db.name }}_examples/')
def {{ db.name }}_examples ():
""" Get a few example rows
---
responses:
200:
description: ...
"""
return _jsonify({{ db.example_rows }})
{% for column in db.columns %}
@app.route('/{{ db.name }}_{{ column }}/<{{ column }}>/')
def {{ db.name }}_{{ column }}({{ column }}):
""" Get row by {{ column }}
---
parameters:
- name: {{ column }}
in: path
type: string
required: true
x-valueType:
- {{ db.columns[column].type }}
x-requestTemplate:
- valueType: {{ db.columns[column].type }}
template: /{{db.name }}_{{ column }}/{% raw %}{{ input }}{% endraw %}
- name: include_similar
in: query
type: boolean
default: false
x-valueType:
- http://schema.org/boolean
x-requestTemplate:
- valueType: http://schema.org/boolean
responses:
200:
description: success
x-responseValueType:{% for response_col in db.columns.values() %}
- path: {{ response_col.name }}
valueType: {{ response_col.type }}{% endfor %}
x-JSONLDContext: /{{ db.name }}_metadata
"""
include_similar = flask.request.args.get("include_similar")
results = []
cursor = get_{{ db.name }}_db ().cursor ()
if include_similar == 'true':
data = cursor.execute (
"SELECT * FROM {{ db.name }} where lower({{ column }}) LIKE lower('%{0}%')".format (
{{ column }}))
else:
data = cursor.execute (
"SELECT * FROM {{ db.name }} where lower({{ column }}) = lower('{0}')".format (
{{ column }}))
for r in data:
row = {}
{% for col in db.columns %}row["{{ col }}"]=r[{{ loop.index0 }}]
{% endfor %}
results.append (row)
cursor.close ()
return _jsonify(results)
{% endfor %}
{% endfor %}
@app.route('/specification/')
def spec ():
""" Get the smartapi specification.
---
responses:
200:
description: ...
"""
text = ""
spec_path = os.path.join (os.path.dirname(__file__), "smartapi.yaml")
if not os.path.exists (spec_path):
port = app.config['SWAGGER']['port']
obj = requests.get (f"http://localhost:{port}/apispec_1.json").json ()
with open (spec_path, "w") as stream:
yaml.dump (obj, stream, default_flow_style=False)
with open (spec_path) as stream:
text = stream.read ()
return text
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='smartBag Server')
parser.add_argument('-p', '--port', type=int, help='Port to run service on.', default=5000)
args = parser.parse_args ()
app.config['SWAGGER']['port'] = args.port
app.run(host='0.0.0.0', port=args.port, debug=True, threaded=True)