[Tutor] Hit Counter

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 29 Jul 2001 18:12:01 -0700 (PDT)


On Sun, 29 Jul 2001, Jon Cosby wrote:

> I'd like to write a hit counter for my Web page. As easy as this would
> seem, it's got me stumped. I'm using a hidden form field:
> 
> <form action="cgi-bin/counter.pyw">
> <input type="hidden" name="Stats" value="Hit Counter">
> </form>
> 
> but I suspect this is where the problem is. Why doesn't the script run
> each time the page loads?


CGI programs don't run until you actually jump into that particular page:
what you have above doesn't acually run the cgi program.  You'll need to
add something like a "submit" button to let people jump into the CGI
program.


Try:

###
<form action="cgi-bin/counter.py">
    <input type="hidden" name="Stats" value="Hit Counter">
    <input type="submit">
</form>
###

on your main web page.  You'll see a button called "submit", and once your
press that, then this will get counter.py program to run.


By the way, there's a nice set of pages from devshed.com that explain more
about CGI programming here:

    http://devshed.com/Server_Side/Python/CGI

which might give some good information.


Hmmm... Let's take a quick glance at your script:

> form = cgi.FieldStorage()
> if form.has_key("Stats")			# Hidden field
> 	InFile = open("count.dat", "r")	# Text file with total hits
> 	Hits = InFile.readline()
> 	x = int(Hits) + 1
> 	h = str(x)
> OutFile = open("count.dat", "w")
> OutFile.write(str(x))
> OutFile.close()

I think the lines starting from the OutFile stuff should also be part of
the if block.  The reason is: what happens if we're not asking our CGI
program for 'stats'?  What ends up happening is that Python won't know
what 'x' or 'h' is in the rest of the program.


It might be good to separate the stats handling part in a separate
function:

###
if form.has_key("Stats"):
    handleStats()

def handleStats():
    InFile = open("count.dat", "r")	# Text file with total hits
    Hits = InFile.readline()
    x = int(Hits) + 1
    h = str(x)
    OutFile = open("count.dat", "w")
    OutFile.write(str(x))
    OutFile.close()
    print "<P><H2>Jon Cosby's web page - Total hits:</H2><br><br> "
    for i in h:
    print "<img src='images/" + i + "silver.gif'>"
    print "</BODY>"
###

Separating it like this should make it a little easier to add more
commands to your CGI.


Hope this helps!