3.11 Streaming Application Output to the Browser

#
3.11 Streaming Application Output to the Browser

By default Albatross buffers all HTML generated from templates inside the execution context and sends a complete page once the template execution has completed (via the `flush_content()` method). The advantage of buffering the HTML is that applications can handle exceptions that occur during execution of the template and prevent any partial results leaking to the browser.

Sometimes your application needs to perform operations which take a long time. Buffering all output while lengthy processing occurs makes the application look bad. Albatross lets you use the `<al-flush>` tag to mark locations in your template file where any accumulated HTML should be flushed to the browser. The only downside to using this tag is that you lose the ability to completely insulate the user from a failure in template execution.

The sample program from this section is supplied in the `samples/templates/stream` directory and can be installed in your web server `cgi-bin` directory by running the following commands.

    cd samples/templates/stream
    python install.py

The `stream.py` program is shown below.

    #!/usr/bin/python
    import time
    from albatross import SimpleContext

    class SlowProcess:
        def __getitem__(self, i):
            time.sleep(1)
            if i < 10:
                return i
            raise IndexError

    ctx = SimpleContext('.')
    templ = ctx.load_template('stream.html')
    ctx.locals.process = SlowProcess()

    print 'Content-Type: text/html'
    print
    templ.to_html(ctx)
    ctx.flush_content()

We have simulated a slow process by building a class that acts like a sequence of 10 elements that each take one second to retrieve.

We must make sure that we send the HTTP headers before calling the template execution (`to_html()` method). This is necessary since the execution of the template is going to cause HTML to be sent to the browser.

Now let's look at the `stream.html` template file that displays the results of our slow process.

    <html>
     <head><title>I think I can, I think I can</title></head>
     <body>
      <p>Calculation is in progress, please stand by.
      <p>
       <al-for iter="n" expr="process">
        <al-flush>
        Stage: <al-value expr="n.value()"><br>
       </al-for>
      <p>All done!
     </body>
    </html>

You can see the program output by pointing your browser at http://www.object-craft.com.au/cgi-bin/alsamp/stream/stream.py.