#!/usr/bin/python # userrep1 - report duration of user logins using SQL database import MySQLdb import cgi import re import sys def template(filename, fillings): text = open(filename).read() def repl(matchobj): if fillings.has_key(matchobj.group(1)): return str(fillings[matchobj.group(1)]) return "" # replace quoted words with value from fillings dictionary text = re.sub("%%(.+?)%%", repl, text) return text fields = cgi.FieldStorage() if not fields.has_key("user"): print "Content-Type: text/plain\n" print "No username" sys.exit(1) def get_userdata(username): db = MySQLdb.connect(passwd="",db="connections", user="bert") db.query("select count(duration) as count," +" sum(duration) as total from logins" +" where username='%s'" % username) res = db.store_result().fetch_row(maxrows=1,how=1) res[0]["username"] = username db.close() return res[0] print "Content-Type: text/html\n" print template("report.tpl", get_userdata(fields["user"].value))