Alternate renderer- generate xml document instead of json

5 views
Skip to first unread message

LawrenceAfloat

unread,
Mar 19, 2009, 10:07:13 AM3/19/09
to TurboGears
I was wanting to have an easy way to turn any output into an xml
document as an alternate to exposing the data using json. And managed
to get this to work. No elegance here.

-- to use
@expose('xml:users', content_type='text/xml')
# creates a root element called users and fills it from users in
template_vars

-- add to app_cfg.py

from xml_render import render_xml
base_config.render_functions.xml = render_xml

-- xml_render.py
import logging, StringIO

_log = logging.getLogger(__name__)

def render_xml(template_name, template_vars, **kwargs):
# turn vars into an xml string.
st = StringIO.StringIO()

def writeElem( obj):
if isinstance( obj, dict ):
for k in obj:
# create element and recurse
if isinstance( obj[k], list ):
# Add multiple elements. Each value should be a
dictionary.
for val in obj[k]:
st.write("<%s>" % k)
writeElem(val)
st.write("</%s>" % k)

elif isinstance( obj[k], dict ):
# element
st.write("<%s>" % k)
writeElem(obj[k])
st.write("</%s>" % k)

else:
st.write("<%s>" % k)
st.write(str(obj[k]))
st.write("</%s>" % k)

elif isinstance( obj, list ):
for val in obj:
writeElem(val)
else:
st.write(str(obj))

# main part of function
try:
st.write("<%s>" % template_name)
if template_vars.has_key(template_name):
writeElem(template_vars[template_name])
st.write("</%s>" % template_name)
_log.debug("render_xml %s", st.getvalue() )
except Exception,ex:
_log.exception("")
return st.getvalue()

jo

unread,
Mar 19, 2009, 12:25:41 PM3/19/09
to TurboGears
I also am looking for a such thing, Lawrence, and I suppose
TGWebservices do that,
when I discover why it works only with tg_format=json in my case.
I was reading documentation and seems by default it should returns
data as xml ....


j

LawrenceAfloat

unread,
Mar 19, 2009, 2:01:40 PM3/19/09
to TurboGears
I should of added that the code is for TG2.


Reply all
Reply to author
Forward
0 new messages