LawrenceAfloat
unread,Mar 19, 2009, 10:07:13 AM3/19/09Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
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()