-
Notifications
You must be signed in to change notification settings - Fork 11
/
views.py
284 lines (201 loc) · 7.43 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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.github_repo import get_readme
from models.entity import make_badge_io
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 send_file
from flask import render_template
from flask import redirect
from flask import url_for
from time import time
import requests
import os
import json
import re
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=""):
return render_template('index.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/person/<person_id>/badge.svg")
def person_badge(person_id):
my_person = Person.query.get(int(person_id))
if not my_person:
abort_json(404, "This person's not in the database")
my_badge_file = make_badge_io(my_person)
return send_file(my_badge_file, mimetype='image/svg+xml')
@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/package/github/<owner>/<repo_name>")
@app.route("/api/package/github/<owner>/<repo_name>.json")
def github_package_endpoint(owner, repo_name):
try:
host, name = package.package_id_from_github_info(owner, repo_name)
except TypeError:
return abort_json(404, "We don't know of any CRAN or PyPI package associated with this GitHub repo. Please report errors at [email protected]. Thanks!")
url = url_for(
"package_endpoint",
host_or_language=host,
project_name=name
)
return redirect(url)
@app.route("/api/package/<host_or_language>/<project_name>/badge.svg")
def package_badge(host_or_language, project_name):
my_id = package.make_id(host_or_language, project_name)
my_package = Package.query.get(my_id)
if not my_package:
abort_json(404, "This package is not in the database")
my_badge_file = make_badge_io(my_package)
return send_file(my_badge_file, mimetype='image/svg+xml')
@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/person")
def email_search():
email = request.args.get("email", None)
ids_and_scores = []
for my_person in Person.query.filter_by(email=email).all():
ids_and_scores += [{
"id": my_person.id,
"impact": my_person.impact,
"impact_percentile": my_person.impact_percentile
}]
return jsonify({"list": ids_and_scores, "count": len(ids_and_scores)})
@app.route("/api/search/<search_str>")
def search(search_str):
ret = autocomplete(search_str)
return jsonify({"list": ret, "count": len(ret)})
@app.route("/test")
def test():
r = requests.get("https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Lawrence_of_arabia_ver3_xxlg.jpg/800px-Lawrence_of_arabia_ver3_xxlg.jpg")
return r.content
@app.route("/api/readme")
def get_readme_endpoint():
readme = get_readme("Impactstory", "depsy")
return jsonify({"readme": readme})
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)