forked from ourresearch/depsy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
224 lines (154 loc) · 5.47 KB
/
views.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
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from app import app
from models.search import autocomplete
from util import elapsed
from models.person import Person
from models import package
from models.package import Package
from models.package_jobs import get_leaders
from models.tags import Tags
from dummy_data import get_dummy_data
from sqlalchemy import orm
from models.package import make_host_name
from flask import make_response
from flask import request
from flask import abort
from flask import jsonify
from flask import render_template
from flask import redirect
from flask import url_for
from time import time
import os
import json
import logging
logger = logging.getLogger("views")
def json_dumper(obj):
"""
if the obj has a to_dict() function we've implemented, uses it to get dict.
from http://stackoverflow.com/a/28174796
"""
try:
return obj.to_dict()
except AttributeError:
return obj.__dict__
def json_resp_from_thing(thing):
hide_keys = request.args.get("hide", "").split(",")
if hide_keys is not None:
for key_to_hide in hide_keys:
try:
del thing[key_to_hide]
except KeyError:
pass
json_str = json.dumps(thing, sort_keys=True, default=json_dumper, indent=4)
if request.path.endswith(".json") and (os.getenv("FLASK_DEBUG", False) == "True"):
logger.info(u"rendering output through debug_api.html template")
resp = make_response(render_template(
'debug_api.html',
data=json_str))
resp.mimetype = "text/html"
else:
resp = make_response(json_str, 200)
resp.mimetype = "application/json"
return resp
def abort_json(status_code, msg):
body_dict = {
"HTTP_status_code": status_code,
"message": msg,
"error": True
}
resp_string = json.dumps(body_dict, sort_keys=True, indent=4)
resp = make_response(resp_string, status_code)
resp.mimetype = "application/json"
abort(resp)
@app.route("/<path:page>") # from http://stackoverflow.com/a/14023930/226013
@app.route("/")
def index_view(path="index", page=""):
if "localhost" in request.url or "dev.depsy.org" in request.url:
# it's us, send the real one
return render_template('index.html')
else:
# it's someone else, send a Coming Soon page.
return render_template('coming-soon.html')
###########################################################################
# API
###########################################################################
@app.route("/api")
def api_test():
return jsonify({"resp": "Hi, I'm Despy!"})
@app.route("/api/person/<person_id>")
@app.route("/api/person/<person_id>.json")
def person_endpoint(person_id):
# data = get_dummy_data("person")
# return json_resp_from_thing(data)
from models.contribution import Contribution
my_person = Person.query.options(orm.subqueryload_all(
Person.contributions,
Contribution.package,
Package.contributions,
Contribution.person
# Person.contributions
)).get(int(person_id))
if not my_person:
abort_json(404, "This person's not in the database")
return json_resp_from_thing(my_person.to_dict())
@app.route("/api/package/<host_or_language>/<project_name>")
@app.route("/api/package/<host_or_language>/<project_name>.json")
def package_endpoint(host_or_language, project_name):
my_id = package.make_id(host_or_language, project_name)
from models.contribution import Contribution
my_package = Package.query.options(
orm.subqueryload_all(Package.contributions, Contribution.person)
).get(my_id)
if not my_package:
abort_json(404, "This package is not in the database")
resp_dict = my_package.to_dict()
return json_resp_from_thing(resp_dict)
@app.route('/api/leaderboard')
@app.route('/api/leaderboard.json')
def leaderboard():
filters_dict = make_filters_dict(request.args)
page_size = request.args.get("page_size", "25")
start = time()
num_total, leaders = get_leaders(
filters=filters_dict,
page_size=int(page_size)
)
leaders_list = [leader.as_snippet for leader in leaders]
ret_dict = {
"num_returned": len(leaders_list),
"num_total": num_total,
"list": leaders_list,
"type": filters_dict["type"],
"filters": filters_dict
}
if "tag" in filters_dict:
tag_obj = Tags.query.filter(Tags.unique_tag==filters_dict["tag"]).first()
ret_dict["related_tags"] = tag_obj.related_tags
ret = json_resp_from_thing(ret_dict)
elapsed_time = elapsed(start)
ret.headers["x-elapsed"] = elapsed_time
return ret
@app.route("/api/search/<search_str>")
def search(search_str):
ret = autocomplete(search_str)
return jsonify({"list": ret, "count": len(ret)})
def make_filters_dict(args):
language = args.get("language", None)
if language:
host_name = make_host_name(language)
else:
host_name = None
full_dict = {
"type": args.get("type", None),
"is_academic": args.get("only_academic", False),
"host": host_name,
"tag": args.get("tag", None)
}
ret = {}
# don't return keys with falsy values, we won't filter by them.
for k, v in full_dict.iteritems():
if v:
ret[k] = v
return ret
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5008))
app.run(host='0.0.0.0', port=port, debug=True, threaded=True)