...

View Full Version : Hit Counter?



Mr. Bubble
12-11-2006, 04:25 AM
Hello all Python programmers,
I am new to python, although I have read lots and learnt lots considering the amount of time that I have been trying.

I was wondering if it is possible to create a web counter in python. I was just looking through the things like:



f = open("somefile.txt")
f = write('Some text that this will write')
f = close


and other functions alike.



Is it possible to do something like this PHP code:



<?php
//Open data
$datafile = file("hits.txt");

// Find out how many hits
$hits = datafile[0];

// Add one
$hits++;

// File handle
$filehandle = fopen("$datafile", 'w');

// Write new hit number
fwrite($filehandle, $hits);

// Save file
fclose($filehandle);

?>


hits.txt



0



in python.


Any help would be greatly appreciated.


Alex.

Kakao
12-11-2006, 11:02 AM
Saving a hit counter in a file is the worst solution. There will be concurrency problems without very good solutions.

The correct approach is to store the hits in a database.

Create the hit_log table:

create table hit_log (hit_time timestamp default current_timestamp);

The hit adder:

import psycopg2 as db

connection = db.connect('host=localhost dbname=test user=user password=password')
cursor = connection.cursor()

query = 'insert into hit_log default values'
cursor.execute(query)

cursor.close()
connection.commit()
connection.close()


To query the hit_log table:

select count(*) from hit_log where hit_time::date = '2006-12-11'::date;

The samples use the postgresql database. Translate it to your database.

Mr. Bubble
12-11-2006, 10:58 PM
Thank you, I will use that.

But is there a way to do it with just a textfile?



Oh yeah... I'm having trouble integrating the python with html, would you be able to help me with that one?



Cheers :thumbsup: ,
Alex.


EDIT:

This is the code that I came up with last night, it works fine (I think) but I dont know how to put it in HTML.



myfile = open("hits.txt", "r")
hits = myfile.read()
myfile.close()
hitsint = int(hits) + 1
newhits = str(hitsint)
myfile = open("hits.txt", "w")
myfile.write(newhits)
myfile.close()



Thanks again,
Alex



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum