CGI Webcounter not quite working...help, please

Dave Harrison dave at nullcube.com
Tue Aug 5 21:01:04 EDT 2003


> I got this webcounter to be called directly (I still can't get it to be 
> called from an HTML file with #exec or #include or anything).

you might want to try embedding the page itself in the code (ugly, but if you're just starting out with python maybe the way to go).

> #!/usr/pkg/bin/python
> 
> print "Content-Type: text/html\n\n"

> print "\n\n"

this part is unnecessary, you already have the two \n's from the statement above it.

> import os
> import string
> 
> print "<HTML>"
> print "<BODY>"
> filenames = os.listdir(os.curdir)
> 
> if "count.txt" in filenames:
>    input = open('count.txt', 'r')
>    i = string.atoi(input.read(1))
> else:
>    i = 0
>    print "File doesnt exist<BR>"
> 
> i = i + 1
> print "This page has been accessed " + `i` + " times.<BR>"
> print "</BODY>"
> print "</HTML>"
> 
> #it doesn't seem to execute this at all
> output = open('count.txt', 'w')
> output.write(`i`)
> output.close()
> 
> Do you see any obvious problems with this?  It works fine when I call it 
> from the command line.

hmmm ... ok well here's how I would do something similar, we dont want to just guess if a file is there, we want it to be there and error else (or so I think, it is a counting script, and a couting script without a file cant really work ;-)

Now while Im sure this isnt the best way to do it (tho I dont think its all that bad either ;-) ....

#!/usr/bin/env python

import string

print 'Content-Type: text/html\n\n'
print '<html><body>'

count = '0'

try:
	count = open('count.txt').read()
	count = string.strip(count)
	num = string.atoi(count)
	print "You are the "+str(num+1)+"th visitor to this page"
except IOError:
	print "No valid file"
except ValueError:
	print "No valid count value"

print '</body></html>'





More information about the Python-list mailing list