forked from slaporte/Disambiguity
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bottle_jsonp.py
41 lines (28 loc) · 1.07 KB
/
bottle_jsonp.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
# Author: Samat Jain <http://samat.org/>
# License: MIT (same as Bottle)
import bottle
from bottle import request, response, route
from bottle import install, uninstall
from json import dumps as json_dumps
class JSONAPIPlugin(object):
name = 'jsonapi'
api = 1
def __init__(self, json_dumps=json_dumps):
uninstall('json')
self.json_dumps = json_dumps
def apply(self, callback, context):
dumps = self.json_dumps
if not dumps: return callback
def wrapper(*a, **ka):
r = callback(*a, **ka)
# Attempt to serialize, raises exception on failure
json_response = dumps(r)
# Set content type only if serialization succesful
response.content_type = 'application/json'
# Wrap in callback function for JSONP
callback_function = request.query.get('callback')
if callback_function:
json_response = ''.join([callback_function, '(', json_response, ')'])
return json_response
return wrapper
install(JSONAPIPlugin())