English 中文(简体)
TurboGears - JSON Rendering
  • 时间:2024-12-22

TurboGears - JSON Rendering


Previous Page Next Page  

The @expose() decorator by default renders html content. However, this can be set to json content type. TurboGears supports json rendering through tg.jsonify.JSONEncoder (**kwargs) class. To render json data simply pass json as content type to expose decorator.

@expose( json )
def jsondata(self, **kwargs):
   return dict(hello =  World )

If /jsondata URL is entered in browser, it will respond by showing −

{"hello": "World"}

jsonp Rendering

jsonp stands for json with padding. It works similar to json output except for the fact that it provides an apppcation/javascript response with a call to a javascript function providing all the values returned by the controller as function arguments.

To enable jsonp rendering you must first append it to the pst of required engines inside your apppcation – config/app_cfg.py

base_config.renderers.append( jsonp )

Write your expose decorator as follows −

@expose( json )
@expose( jsonp )
def jsonpdata (self, **kwargs): 
   return dict(hello =  World )

When accessing /jsonpdata?callback = callme, you should see −

callme({"hello": "World"});
Advertisements