render an xml view with rest

29 views
Skip to first unread message

Mamisoa Andriantafika

unread,
Jun 11, 2016, 5:25:38 PM6/11/16
to web2py-users
Hi,

With this code:

@request.restful()
def icd10():
   
import libxml2
    icd10_xml
= libxml2.parseDoc(open('/home/www-data/web2py/applications'+URL('static','icd10/icd10cm/Tabular.xml'),'r').read())
    response
.view = 'generic.xml'
   
def GET(**vars):
        search_str
= request.vars.search
        xpath_req
= '//chapter/section/diag/desc[contains(text(),"'+search_str+'")]'
        diags
= icd10_xml.xpathEval(xpath_req)
        concat
= '<?xml version="1.0" encoding="utf-8"?><main>'
       
for diag in diags:
            diag_str
= str(XML(diag))
            concat
= concat + diag_str
        concat
= concat + '</main>'
       
return concat
   
return locals()

I get an HTML view instead of XML.

Why?

Mike

Anthony

unread,
Jun 11, 2016, 8:54:43 PM6/11/16
to web2py-users
How are you calling that action? The content type won't be set to XML unless you use a .xml extension in the request (or explicitly set the content-type header yourself).

Two additional observations:
  1. You have specified generic.xml as the view, but your code builds an XML string, so there would seem to be no point in passing anything to the generic.xml view.
  2. Because your code returns a string, no view will be executed anyway, as views are only executed when actions return a dictionary.

Anthony

Mamisoa Andriantafika

unread,
Jun 12, 2016, 5:03:13 AM6/12/16
to web2py-users
Thanks for your input.

I removed the response.view and added the xml extension in the request:

https://localhost/testapp/api/icd10.xml?search=string

and it worked. Is there any way to get an xml view without adding the xml extension?

Anthony

unread,
Jun 12, 2016, 11:13:56 AM6/12/16
to web2py-users
On Sunday, June 12, 2016 at 5:03:13 AM UTC-4, Mamisoa Andriantafika wrote:
Thanks for your input.

I removed the response.view and added the xml extension in the request:

https://localhost/testapp/api/icd10.xml?search=string

and it worked. Is there any way to get an xml view without adding the xml extension?

Just return XML. In many cases, the content-type HTTP header should be set to XML as well for the client to function properly (i.e., so the client knows the content is XML). web2py sets that automatically if you include the .xml extension. Otherwise, you simply have to set that header yourself (see response.headers here).

Anthony
Reply all
Reply to author
Forward
0 new messages