# HG changeset patch # User Daniele Nicolodi # Date 1320401232 -3600 # Node ID f6f93996acf46f1b27890d7271365c5eae351f30 # Parent 498ed3c29a0a0a7c2eb6e4fcdd962036cdf8658f Show timezone information for dates extracted from MySQL database. The convenction is that all datetimes fields in the database are stored as UTC times. Therefore we customize the mysql python connector to convert DATETIME fields to an instance of a datetime subclass with UTC tzinfo, and string representation showing the timezone name, instead of the timezone naive defaul. diff -r 498ed3c29a0a -r f6f93996acf4 src/ltpdarepo/__init__.py --- a/src/ltpdarepo/__init__.py Thu Nov 03 20:30:46 2011 +0100 +++ b/src/ltpdarepo/__init__.py Fri Nov 04 11:07:12 2011 +0100 @@ -1,10 +1,13 @@ from urlparse import urlparse, urljoin +from datetime import datetime from flask import Flask, g, request, session, render_template, Markup, redirect, flash, url_for from werkzeug.exceptions import default_exceptions, InternalServerError, HTTPException from pkg_resources import get_distribution import MySQLdb as mysql +import MySQLdb.converters +import dateutil.tz from ltpdarepo.security import secure, require, authenticate @@ -16,6 +19,26 @@ secure(app) +class datetimeutc(datetime): + # subclass of `datetime.datetime` with default string + # representation including the timezone name + def __str__(self): + return self.strftime('%Y-%m-%d %H:%M:%S %Z') + + +# customize mysql types conversion for datetime fields to return +# timezone aware objects in the UTC timezone +def datetime_or_none_utc(s): + value = mysql.converters.DateTime_or_None(s) + if value is not None: + value = datetimeutc(value.year, value.month, value.day, value.hour, + value.minute, value.second, value.microsecond, + tzinfo=dateutil.tz.tzutc()) + return value +conversions = mysql.converters.conversions.copy() +conversions[mysql.constants.FIELD_TYPE.DATETIME] = datetime_or_none_utc + + @app.before_request def before_request(): # get version information from package @@ -28,7 +51,7 @@ # open database connection g.db = mysql.connect(host=app.config['HOSTNAME'], db=app.config['DATABASE'], user=app.config['USERNAME'], passwd=app.config['PASSWORD'], - charset='utf8') + charset='utf8', conv=conversions) # validate schema revision curs = g.db.cursor() diff -r 498ed3c29a0a -r f6f93996acf4 src/ltpdarepo/views/browse.py --- a/src/ltpdarepo/views/browse.py Thu Nov 03 20:30:46 2011 +0100 +++ b/src/ltpdarepo/views/browse.py Fri Nov 04 11:07:12 2011 +0100 @@ -229,7 +229,7 @@ value = dateutil.parser.parse(string, dayfirst=True, yearfirst=True, default=default) return datetime.__new__(cls, value.year, value.month, value.day, value.hour, - value.minute, value.second, value.microsecond, value.tzinfo) + value.minute, value.second, value.microsecond, value.tzinfo) def __str__(self): return self.strftime('%Y-%m-%d %H:%M:%S %Z')