dynamically creating html code with python...

Jerry Hill malaclypse2 at gmail.com
Mon Aug 11 16:07:22 CEST 2008


On Mon, Aug 11, 2008 at 9:15 AM,  <anartz at anartz.cjb.net> wrote:
> [CODE]
> f=StringIO.StringIO()
> f.write('<html><head><title>data analysis</title></head><body>')
> f.write(urllib.urlopen("http://localhost/path2Libs/myLibs.py", urllib.urlencode(TheData)))
> f.write("</body></html>")
>
> print "Content-type: text/html\n"
> print f.read()
> f.close()
> [/CODE]
>
> What is wrong with this approach/code? Is there an easier way of doing it?

A StringIO object works a lot like a file.  When you write to it, it
keeps track of the current position in the file.  When you read from
it, it reads from the current position to the end of the file.  Once
you're done writing to the StringIO object, you can rewind the
position to the beggining and then read to the end, like this:

f = StringIO.StringIO()
f.write('This is some data')
f.seek(0)
print f.read()

StringIO objects also have a special getvalue() method, which allows
you to get the entire contents without changing the current position.
You can replace your f.read() with f.getvalue() without having to mess
with seek(), but then your code won't work with real files, if that's
important.

-- 
Jerry



More information about the Python-list mailing list