Generating static HTML from TurboGears (Part 1)

Filed under: turbogears 

I'm exploring caching options for use with TurboGears, and of course, the penultimate cache is when you are serving static HTML pages from a webserver (like Lighty or Apache) rather than dynamic content from a framework.

The key to generating the static HTML files is to use what is known as a filter. CherryPy lets you attach filters at several points in the request processing chain. In this case, I wanted to intercept the request right before it's returned to the browser and dump it to a file:

from cherrypy.filters.basefilter import BaseFilter
class StaticOutFilter ( BaseFilter ):
    def before_finalize ( self ):
        if cherrypy.response.status is None:
            path = os.path.join ( 'path/to/static/cache',
                                  *tuple ( cherrypy.request.path.split ( '/' ) ) ) + '.html'
            try:
                os.makedirs ( os.path.dirname ( path ) )
            except OSError:
                pass
            file ( path, 'w' ).writelines ( cherrypy.response.body )

class Root ( controllers.RootController ):
    _cp_filters = [ StaticOutFilter ( ) ]

That's it! Now the content is stored as static HTML files in a directory hierarchy that mirrors the URL hierarchy in my application. There are many caveats and limitations (and probable dangers - I'll need to analyze the writer code to make sure no path manipulation can be done), but it's a start.

Read Part 2 of this Article



0 comments Leave a comment