#!/usr/local/bin/python -tt # # graph-weight.py: A CGI-like script for using gnuplot to draw a plot of # weights pulled from SQL. import cgitb; cgitb.enable() import datetime import os import sys import time import pg # When executed as a CGI, HOME isn't set. But we need it for a temp # directory. if not os.environ.has_key('HOME'): os.environ['HOME'] = 'XXX' # TODO: replace def getWeightHistory(conn): weights_by_date = {} sql = "SELECT date, weight FROM fitness_weight" r = conn.query(sql) for result in r.getresult(): dateStr = result[0] dateTime = time.strptime(dateStr, '%Y-%m-%d') date = datetime.date(dateTime.tm_year, dateTime.tm_mon, dateTime.tm_mday) weight = result[1] weights_by_date[date] = weight return weights_by_date def isPlotOutOfDate(plot_file): if not os.path.exists(plot_file): return True mtime = os.path.getmtime(plot_file) now = time.time() # If file is less than 15 minutes old, we'll keep it if (now - mtime < 60 * 15): return False return True def generatePlot(weight_history, plot_file): weight_dates = weight_history.keys() weight_dates.sort() first_date = weight_dates[0] last_date = weight_dates[-1] f = os.popen('gnuplot', 'w') try: print >>f, "set terminal png medium transparent size 960,400" print >>f, "set out '%s'" % (plot_file) print >>f, "set grid" print >>f, "set xdata time" print >>f, "set timefmt \"%Y-%m-%d\"" print >>f, "set xrange [\"%s\":\"%s\"]" % (first_date, last_date) print >>f, "set xlabel 'Date'" print >>f, "set ylabel 'Weight'" print >>f, "plot '-' using 1:2 title 'Weight' with points, '-' using 1:2 title 'Smoothed Weight' with lines lw 3 smooth bezier" for date in weight_dates: print >>f, "%s %s" % (date, weight_history[date]) print >>f, "e" for date in weight_dates: print >>f, "%s %s" % (date, weight_history[date]) print >>f, "e" finally: f.close() plot_file_name = '%s/.weight.png' % os.environ['HOME'] if isPlotOutOfDate(plot_file_name): conn = pg.DB(dbname='XXX', host='XXX', user='XXX') # TODO: Fill in these values weight_history = getWeightHistory(conn) generatePlot(weight_history, plot_file_name) plot_file = file(plot_file_name, 'rb') # After this point, we've already committed to sending the web page, # so try really hard not to generate any errors. print 'Content-Type: image/png' print sys.stdout.write(plot_file.read())