-
Notifications
You must be signed in to change notification settings - Fork 71
/
util.py
42 lines (34 loc) · 1.13 KB
/
util.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
from functools import wraps
from flask import jsonify, request, current_app
def safe_float(s, range, default=False):
try:
f = float(s)
except:
return default
if f > range[1]:
return default
if f < range[0]:
return default
return f
# json endpoint decorator
def json(func):
"""Returning a object gets JSONified"""
@wraps(func)
def decorated_function(*args, **kwargs):
return jsonify(func(*args, **kwargs)[0]), func(*args, **kwargs)[1]
return decorated_function
# from farazdagi on github
# https://gist.github.com/1089923
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
data = str(func(*args, **kwargs)[0].data)
content = str(callback) + '(' + data + ')'
mimetype = 'application/javascript'
return current_app.response_class(content, mimetype=mimetype), func(*args, **kwargs)[1]
else:
return func(*args, **kwargs)
return decorated_function