< Karrigell

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

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.