Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import ThreadLocalData # location of appropriate TZ info
- import sqlalchemy.ext.declarative as declarative
- from sqlalchemy import types, Column, Integer, String
- from pytz import UTC as _UTC
- OrmBase = declarative.declarative_base()
- class UTCEnforcedDateTime(types.TypeDecorator):
- """DateTime type to ensure datetime objects are offset-aware UTC."""
- impl = types.DateTime
- def process_bind_param(self, value, engine):
- if (value is not None) and (value.tzinfo != _UTC):
- raise Exception("illegal naive datetime instance!")
- return value
- def process_result_value(self, value, engine):
- if value is not None:
- return value.replace(tzinfo = _UTC)
- return value
- class TableDefMixin(object):
- def _EnsureUTC(self, AttrName, dt):
- if dt == None:
- return dt
- assert dt.tzinfo == None, \
- "offset-aware datetime not expected"
- tz = ThreadLocalData.LocalTZ
- #Convert naive time to local time...
- # - normalize is needed to deal with DST funkiness
- dt_tz = tz.normalize(tz.localize(dt))
- #return the time as UTC...
- return dt_tz.astimezone(_UTC)
- class User(OrmBase, TableDefMixin):
- __tablename__ = "user"
- id = Column(Integer, primary_key = True, autoincrement = True)
- login = Column(String(100), index = True, unique = True)
- creation_date = Column(UTCEnforcedDateTime, nullable = False)
- last_login = Column(UTCEnforcedDateTime, nullable = True)
- #<snip>
- #Nasty hack (?) is here!
- utcConversionList = ["creation_date", "last_login"]
- User._EnsureUTC.__dict__["__sa_validators__"] = utcConversionList
Advertisement
Add Comment
Please, Sign In to add comment