Mercurial > hg > ltpdarepo
changeset 156:f6f93996acf4
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.
author | Daniele Nicolodi <daniele@grinta.net> |
---|---|
date | Fri, 04 Nov 2011 11:07:12 +0100 |
parents | 498ed3c29a0a |
children | 5af343faf647 |
files | src/ltpdarepo/__init__.py src/ltpdarepo/views/browse.py |
diffstat | 2 files changed, 25 insertions(+), 2 deletions(-) [+] |
line wrap: on
line diff
--- 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()
--- 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')