Jump to content

Toolserver:Python/Click tracker

From mediawiki.org

This page was moved from the Toolserver wiki.
Toolserver has been replaced by Toolforge. As such, the instructions here may no longer work, but may still be of historical interest.
Please help by updating examples, links, template links, etc. If a page is still relevant, move it to a normal title and leave a redirect.

This simple click tracking script is intended to demonstrate use of Python WSGI.

Advanced users may wish to try using environ.get('PATH_INFO') instead of standard cgi parameters.

#!/usr/bin/env python
# click.py written by Dispenser 2010
# Released into the public domain
import cgi, time

def main(environ, start_response):
	# environ is equivalent to "os" module
	form = cgi.FieldStorage(environ['wsgi.input'], # File upload/POST data
	                        environ=environ,       # Environment variables (QUERY_STRING)
	                        keep_blank_values=0)   # Discard "&empty="
	button = form.getfirst('button', '')
	usergroup = form.getfirst('usergroup', '')
	agent = environ.get('HTTP_USER_AGENT', '') # which browser
	
	# We do it the simple way without much pre-processing, and just use files
	if button and usergroup: # "validate input"
		f = open( time.strftime('./clicktrack/%Y%m%d.log'), 'a')
		f.write('\t'.join( (usergroup, button, agent, time.strftime("%H:%M:%S\n"),) ))
		f.close()
	
	# HTTP 204: acknowledged with a blank document
	# Set the expiration in the past so the browser doesn't cache the request
	start_response('204 No content', [("Pragma","no-cache"), ("Expires","Fri, 01 Jan 1990 00:00:00 GMT"), ("Cache-Control","no-cache, must-revalidate")])
	return ['']

if __name__ == "__main__":
	from flup.server.fcgi import WSGIServer
	WSGIServer(main).run()

JavaScript to track events without an AJAX object or iframe.

var trackerUrl = "/bin/click.py";
var UserGroup = "editor";

function addClickTrackingEvents(){
	var a = document.getElementsByTagName('A');
	for(var i=0; a[i]!=null; i++){
		if(a[i].id){ // Only report on links with IDs
			a[i].onmousedown = function(){
				// This is a sneaky of adding the tracking without using an HTTP redirect.
				// It works by loading an image thus sending the URL.
				// We don't care what it sends back, but to be safe it's blank
				if(document.images){
					(new Image).src=[trackerUrl,'?button=',this.id,'&usergroup=',UserGroup].join("");
					return true;
				}
			}
		}
	}
}

// Run addClickTrackingEvents() after the document has loaded
window.onload = addClickTrackingEvents;

Category:Programming languages