[mod_python] Import a module into a variable value

Mike Looijmans nlv11281 at natlab.research.philips.com
Tue Dec 5 01:21:14 EST 2006

Why not just re-read the file on every request?

The caching you are doing now is also done by the operating system. You won't be really reading from 
disk when you do a read. Note that using:

_html = f.read()

is much more efficient than reading into an array and then joining the lines together - unless 
removing newline characters was what you had in mind (which I seriously doubt because it might mess 
up the text).

In fact, a one-liner will do:

return open('/var/www/html/carconsumption.com/index.html', 'r').read() % _d

Mike Looijmans
Philips Natlab / Topic Automation

Clodoaldo wrote:
> I'm doing a very light templating in a publisher program.
> There is a html template read from the index.html file in which
> '%(variable)s' are replaced.
> This code reads the template from the file:
> f = open('/var/www/html/carconsumption.com/index.html', 'r')
> _html = ''.join(f.readlines())
> f.close()
> And then inside index() at return time the usual substitution:
>   return C._html % _d
> Editing a file with the extension .html is nice with editors with html
> syntax highlighting, completion and other things. The only problem
> with this approach is that the file index.html is not reloaded when
> changed.
> I know i could just use a generic handler with PSP as templating. But
> the publisher is so convenient and as the new importer in 3.3 is full
> of tricks like importing modules with any extension i would like to
> know if there is some way to import a whole module into a variable
> value preventing it from being interpreted as python code.
> If the above is nonsense what would be a better approach for
> templating within publisher programs or just to solve the not
> reloadable index.html file?
> Regards,

More information about the Mod_python mailing list