JSONP property for cherrypy


/ Published in: Python
Save to your folder(s)

This is a @property to take care of jsonp stuff if you're using CherryPy.
In your Javascript, (you're using JQuery, right?) you can do
`
$.ajax({url:"localhost:8080/MyMethod", data:{'arg1':'foo'}, dataType:"jsonp", success:onMyMethodComplete});
`
and you will get back your JS datastructure without having to worry about the jsonp stuff yourself.


Copy this code and paste it in your HTML
  1. import simplejson
  2. def jsonp(func):
  3. def foo(self, *args, **kwargs):
  4. callback, _ = None, None
  5. if 'callback' in kwargs and '_' in kwargs:
  6. callback, _ = kwargs['callback'], kwargs['_']
  7. del kwargs['callback'], kwargs['_']
  8. ret = func(self, *args, **kwargs)
  9. if callback is not None:
  10. ret = '%s(%s)' % (callback, simplejson.dumps(ret))
  11. return ret
  12. return foo
  13.  
  14. class Server(object):
  15. @cherrypy.expose
  16. @jsonp
  17. def MyMethod(self, arg1):
  18. #do something with arg1
  19. return 'Works'

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.