From Wikibooks, open books for an open world
< Karrigell
Jump to navigation Jump to search

A program to count the number of visits to a page

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

if not hasattr(Session(),'page_counter'):
   c += 1
   f = open('counter','w')
   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