Wednesday, July 17, 2019

A Simple Persistent Page Counter for Python

I have been playing with Gopherspace (yes, that is still a thing) and Flask-Gopher. I needed a simple visitor counter for Python 3.7 so I can see how many times a page loaded.

Here is the solution I came up with. It creates a text file called counter.dat and stores a number in it.  Each time the code runs, the number in the file increments.

I used pathlib to solve file path differences between Unix and Windows.
I hope it helps you!


from pathlib import Path

#Change path to the Linux or Windows folder where your counter .dat file will live.
data_folder = Path('c:/Users/change_this/Documents/')
counter = data_folder / 'counter.dat'

try:
    with open(counter, mode='r') as f:
        count = int(f.read())+1

    with open(counter, mode='w') as f:
        f.write(str(count))
        f.close()

except:
    print('first run exception fired')
    #create the counter.dat file on first run
    count = 1
    with open(counter, mode='w') as f:
        f.write(str(count))
        f.close()

print('You are visitor number ' + str(count))

No comments: