[Cubicweb] demote_to_html and main_stream

Adrien Di Mascio adrien.dimascio at logilab.fr
Fri Apr 1 08:02:21 CEST 2011

Hi Carlos,

On 01/04/2011 05:49, Carlos Balderas wrote:
> ERROR: an exception occurred while calling
> js_update_events_calendar([]): 'CubicWebTwistedRequestAdapter' object
> has no attribute 'main_stream'
> The view CalendarEvent in web/views/calendar.py uses the method
> "demote_to_html" which is needed to let fullcalendar jquery plugin to
> work in this view.

demote_to_html() is known to break with ajax views and this is a bug, as 
reported by the two tickets below :

- http://www.cubicweb.org/ticket/712309
- http://www.cubicweb.org/ticket/663360

> My first question is about the missing "main_stream" attribute, I am not
> sure why that is, as far as I see It is just about assign another type
> of value. e.i.
> 1.0 Transitional//EN"
> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n'

``main_stream`` is the object responsible for actually writing html in a 
real Python StringIO-like object. When you implement an HTML view, the 
``self.w`` function you keep calling is actually an indirection to this 
stream's ``write()`` method (see. `cubicweb.utils.HTMLStream` class). 
It's also the object responsible for writing the doctype declaration in 
your page.

When you're in an ajax context, for some reason (historical mainly), the 
``HTMLStream`` class is not used and therefore ``demote_to_html`` 
crashes. One quick fix you could try would be to put all the code in 
``demote_to_html()`` in a conditional block :

     def demote_to_html(self):
         if self.json_request: # json_request is really badly named
             self.main_stream.doctype = TRANSITIONAL_DOCTYPE_NOEXT
             self.main_stream.xmldecl = u''
             # make sure @xhtmlize will not reset content-type to xhtml
             self.xhtml_content_type = lambda: 'text/html'

I'm not absolutely sure it will work but it's worth trying. A better fix 
should be implemented in CubicWeb.

> My second question is about the use of @xhtmlize decorator, since the
> view I'd like to use uses "demote_to_html" looks like I don't really
> know what I am doing.. =S , so, Is it necesary to use @xhtmlize
> decorator to return the html code by this cubicweb/ajax method?

@xhtmlize is needed because it's what will set the HTTP response header 
``Content-type`` to ``text/html`` (or ``application/xhtml+xml`` if your 
browser supports it). On the javascript side, when the AJAX response is 
received, this header is used to determine how to interpret the response 
: json / html / etc.

Adrien Di Mascio - LOGILAB, Paris (France).
Formations - http://www.logilab.fr/formations
Développements - http://www.logilab.fr/services
Gestion de connaissances - http://www.cubicweb.org/

More information about the Cubicweb mailing list