BW
Main Menu
Home
Contact Bill
lynda.com FAQ
Facebook
Linked In
Twitter
AMTP
Bio
Hire Bill
Bill’s Music
BW Whois
Boulder Pledge
UBE-Related
Blog
CGI Scripts
CMS Project
Music DB
Creative HTML
The CGI Book
Perl Book
BillyDos
Privacy
The End
· Sponsors ·
lynda.com video tutorials
amazon.com
Rheumatoid Arthritis
Site Design: Bill Weinman

CGI Scripts by Bill Weinman

bw-counter [perl] [python]

As I prepare to deliver my Python 3 course for lynda.com, I am rewriting a number of my small perl scripts in Python. This is part of that effort.

This is a simple hit counter for your web page. It is run from a server-side include (SSI). This version is written in Python 3 (for Python 3.1 or later). There is also a Perl version.

On an Apache server you put something like this in your page:

  <!--#include virtual="/bw-counter/bw-counter.py" -->

The result should look something like this:

2,263

You will need to create a file for the count, and make sure the web server has read and write permission for that file (i.e., chmod 666 filename on a Unix system). The full path to that file should go in the $count_file variable near the top of the script.

Here is the source code for bw-counter.py. Copy/paste this code into your text editor, and make sure that the line

#!/usr/bin/python3
is the first line in the file. You may need to adjust the path to python3 if you have it installed somewhere else.

#!/usr/bin/python3
# bw-counter.py by Bill Weinman <http://bw.org/>
# Copyright (c) 1995-2010 The BearHeart Group, LLC
# created 2010-02-01
#
# A simple incremental counter for a web page. (Python version)
#
# The author grants permission to use and modify this program as you like. 
# All other rights and ownership are reserved by the author. 
#

import sys
from os import path
me = path.basename(sys.argv[0])

class Counter():
    countFile = "/full/path/to/count"
    def __init__(self, countFile = None):
        if countFile: self.countFile = countFile
        try: 
            self.fh = open(self.countFile, mode = 'tr+')
        except IOError as e:
            error(e)

    def next(self):
        try:
            self.count = int(self.fh.readline() or 0) + 1
            self.fh.seek(0)
            print('{:d}'.format(self.count), file = self.fh)
            self.fh.flush()
        except IOError as e:
            error(e)
        return self.count

def main():
    header()
    count = Counter()
    print('{:,d}'.format(count.next()))

def header():
    print('Content-type: text/html\n\n', end = '')    # minimal mime header for CGI
    print()

def error(e):
    print( '{}: {}'.format(me, e))
    sys.exit(0)

if __name__ == '__main__': main()


I installed a skylight. Now the folks above me are mad.
At BHG Worldwide Headquarters it is now eighteen till ten, on Wednesday, 24 April 2024.
·/.