[mod_python] Import a module into a variable value

Jorey Bump list at joreybump.com
Sat Dec 2 09:51:46 EST 2006


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()

Try putting this in a function.

> And then inside index() at return time the usual substitution:
> 
>   return C._html % _d

Call your function instead:

     return page(_d)

> Editing a file with the extension .html is nice with editors with html
> syntax highlighting, completion and other things. 

Yes, that's true.

> The only problem
> with this approach is that the file index.html is not reloaded when
> changed.

There are times when I'll create a large HTML snippet in an editor, then 
copy and paste it into a string variable in a module. As you point out, 
it might not get reloaded. But it could depend on how/where you read in 
the template text.

> 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.

Regardless of the extension, an imported module should still contain 
Python code. If you are leveraging the new importer in 3.3, this 
shouldn't be much of a problem. When you finish editing your page, wrap 
in a string variable and save it as a module. Either maintain a master 
version to paste from, or comment out the variable wrapper whenever you 
open it in your HTML editor. I suspect that most edits will be so minor 
after the initial creation of your template, that you won't depend on 
the syntax highlighting.

> 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?

Try the technique above, or store the page in a db, or check out an 
existing templating system... I have my own library for creating HTML, 
and build my templates from that. The way I normally do it means that 
it's vulnerable to the reloading issue (I put all of the code for my 
applications in packages), but it needn't be so, especially with the new 
importer.



More information about the Mod_python mailing list