Peter's Blog

Redefining the Impossible

Generating HTML and displaying it in Python


Under Windows the following python uses the Win32 extensions to launch whatever default html browser you have showing the appropriate html file:

import win32api

strPathToFile = "c:\\path\\for\\file.html"

win32api.ShellExecute( 0, "Open", strPathToFile, None, None, 0)

This is coolest when combined with the Cheetah Template Library:

   1  import Cheetah.Template
   2  
   3  #
   4  # Define report template. This is mostly html, the $ stuff will be
   5  # replaced by Cheetah.
   6  #
   7  strTemplate = """
   8  <html>
   9  <head>
  10  <title>$title</title>
  11  <head>
  12  <body>
  13  Hello $name, how are you today?
  14  </body>
  15  </html>
  16  """
  17  
  18  #
  19  # Build a dictionary of the $ symbols above and what should be displayed instead
  20  #
  21  oDict = { 'title': "This is my title", 'name': 'Peter'}
  22  
  23  #
  24  # Cheetah does it's magic
  25  #
  26  oHtml = Cheetah.Template.Template( strTemplate, [oDict])
  27  
  28  #
  29  # Write html to file and display it.
  30  #
  31  open( 'c:\\tmp\\file.html', 'wt').write( str(oHtml))
  32  win32api.ShellExecute( 0, "Open", 'c:\\tmp\\file.html', None, None, 0)

Cheetah is very powerful. The following code demonstrates a few features:

  • can use for loops to generate the rows of a table
  • instances of classes can be passed into cheetah and it can access member variables or call member functions
  • it tends to work first time the way you think it will.
   1  #
   2  # Show test report
   3  #
   4  
   5  import Cheetah.Template
   6  
   7  strTemplate = """
   8  $wiffle.blub
   9  $wiffle.nub
  10  $wiffle.grub()
  11  <table>
  12  <tr>
  13  #for $awiff in $wiffles
  14  <td>$awiff.blub</td>
  15  <td>$awiff.nub</td>
  16  <td>$awiff.grub()</td>
  17  #end for
  18  </tr>
  19  </table>
  20  """
  21  
  22  class Wiff:
  23      def __init__( self):
  24          self.blub = 'blublub'
  25          self.nub = 'nubnubnub'
  26      def grub( self):
  27          return 'i am grub'
  28  
  29  oDict = { 'wiffle': Wiff(), 'wiffles': [ Wiff(), Wiff(), Wiff()] }
  30  
  31  oHtml = Cheetah.Template.Template( strTemplate, [oDict])
  32  print str(oHtml)

Filed under: cheetah python windows

Comments are Closed