[Tutor] Reading and outputting HTML

Michael P. Reilly arcege@shore.net
Mon, 5 Feb 2001 07:45:14 -0500 (EST)


> #!C:/Python/python.exe -u
> 
> print "Content-Type: text/html\n\n"
> 
> import cgi
> import webbrowser
> #
> #
> form =3D cgi.FieldStorage()
> print "saving html to file..."
> htmlfile =3D open("./webpages/tester.html", "w")
> htmlfile.write(form["editarea"].value)
> test =3D htmlfile.read()
> print "test file output..."
> print test
> 
> webbrowser.open("./webpages/tester.html")
> 
> 
> 
> I would like to display the generated HTML , but the page Displays garble=
> d
> on the SERVER!!?? I just can=B4t get my code to edit, store and re-displa=
> y
> HTML files :-(

Looking at the code, the "blaring" errors are that you:
a) Reading to a file that is only openned for writting; change the
   openning option from 'w' to 'w+', for "read and write".
b) Should be reading an empty string from htmlfile since you haven't
   moved the file pointer back to the beginning of the file.

   With every file, there is a pointer where you are looking, writing
   to the file moves it.  Reading would pick up where it left off, in
   this case at the end of the file.  You want to use the "seek" method
   to move the file pointer to the beginning.
 htmlfile = open("./webpages/tester.html", "w+")
 htmlfile.write(form["editarea"].value)
 htmlfile.seek(0)
 test = htmlfile.read()
c) You are attempting to open a browser (client) session from a web
   server.  There is already a browser open (which submitted your
   form); you should be using that, by writing to stdout.  You are
   already doing that with the print statements.

Since you want to tell the browser to open another file, you would want
to send a redirection HTTP response.  Change the first print to:
  print 'Location: /tester.html'
  print

This assumes that \webpages\ is your DocumentRoot setting in your web
server software.

Good luck,
  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------