[PATCH phosphor-rest-server] Add support for serving jsonp

OpenBMC Patches openbmc-patches at stwcx.xyz
Wed Mar 30 02:40:57 AEDT 2016


From: Brad Bishop <bradleyb at fuzziesquirrel.com>

Jsonp adds a javascript wrapper to json responses.  It allows client
applications to work around cross domain restrictions imposed by some
browsers.  For more information on jsonp:
https://en.wikipedia.org/wiki/JSONP

To get a jsonp response, an application adds a callback url parameter
with the desired name of the wrapper:
https://192.168.252.1/list?callback=my_callback
---
 obmc-rest | 30 ++++++++++++++++++++++++++++--
 1 file changed, 28 insertions(+), 2 deletions(-)

diff --git a/obmc-rest b/obmc-rest
index 2eaa223..0bc67ef 100644
--- a/obmc-rest
+++ b/obmc-rest
@@ -751,6 +751,32 @@ class JsonApiErrorsPlugin(object):
         return json_response
 
 
+class JsonpPlugin(JsonApiErrorsPlugin):
+    ''' Json javascript wrapper. '''
+    name = 'jsonp'
+    api = 2
+
+    def __init__(self, **kw):
+        super(JsonpPlugin, self).__init__(**kw)
+
+    @staticmethod
+    def to_jsonp(json):
+        jwrapper = request.query.callback or None
+        if(jwrapper):
+            response.set_header('Content-Type', 'application/javascript')
+            json = jwrapper + '(' + json + ');'
+        return json
+
+    def apply(self, callback, route):
+        def wrap(*a, **kw):
+            return self.to_jsonp(callback(*a, **kw))
+        return wrap
+
+    def json_errors(self, res, error):
+        json = super(JsonpPlugin, self).json_errors(res, error)
+        return self.to_jsonp(json)
+
+
 class RestApp(Bottle):
     def __init__(self, bus):
         super(RestApp, self).__init__(autojson=False)
@@ -765,9 +791,9 @@ class RestApp(Bottle):
     def install_plugins(self):
         # install json api plugins
         json_kw = {'indent': 2, 'sort_keys': True}
-        self.install(JSONPlugin(**json_kw))
-        self.install(JsonApiErrorsPlugin(**json_kw))
         self.install(AuthorizationPlugin())
+        self.install(JsonpPlugin(**json_kw))
+        self.install(JSONPlugin(**json_kw))
         self.install(JsonApiResponsePlugin())
         self.install(JsonApiRequestPlugin())
         self.install(JsonApiRequestTypePlugin())
-- 
2.7.1




More information about the openbmc mailing list