Last modified on 21 September 2010, at 13:43

Karrigell/Counter

A program to count the number of visits to a page

# the counter is stored in a file called "counter"
try:
   c = int(open('counter').read())
except IOError:
   c = 0

if not hasattr(Session(),'page_counter'):
   c += 1
   f = open('counter','w')
   f.write(str(c))
   f.close()
   Session().page_counter = c

print Session().page_counter,'visits'


The session ensures that the visit in counted only once for each visitor, even if he reloads the page 100 times

You can of course include this script in another one (Include('counter.py'))

You could even pass a filename to the Include function, if you need to manage a different counter for each page