Guest User

SQLAlchemy validation hackfest

a guest
Jun 30th, 2011
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. import ThreadLocalData # location of appropriate TZ info
  2. import sqlalchemy.ext.declarative as declarative
  3. from sqlalchemy import types, Column, Integer, String
  4. from pytz import UTC as _UTC
  5.  
  6. OrmBase = declarative.declarative_base()
  7.  
  8. class UTCEnforcedDateTime(types.TypeDecorator):
  9.     """DateTime type to ensure datetime objects are offset-aware UTC."""
  10.     impl = types.DateTime
  11.    
  12.     def process_bind_param(self, value, engine):
  13.         if (value is not None) and (value.tzinfo != _UTC):
  14.             raise Exception("illegal naive datetime instance!")
  15.         return value
  16.    
  17.     def process_result_value(self, value, engine):
  18.         if value is not None:
  19.             return value.replace(tzinfo = _UTC)
  20.         return value
  21.  
  22. class TableDefMixin(object):
  23.     def _EnsureUTC(self, AttrName, dt):
  24.         if dt == None:
  25.             return dt
  26.         assert dt.tzinfo == None, \
  27.                "offset-aware datetime not expected"
  28.         tz = ThreadLocalData.LocalTZ
  29.         #Convert naive time to local time...
  30.         # - normalize is needed to deal with DST funkiness
  31.         dt_tz = tz.normalize(tz.localize(dt))
  32.         #return the time as UTC...
  33.         return dt_tz.astimezone(_UTC)
  34.  
  35. class User(OrmBase, TableDefMixin):
  36.     __tablename__ = "user"
  37.     id = Column(Integer, primary_key = True, autoincrement = True)
  38.     login = Column(String(100), index = True, unique = True)
  39.     creation_date = Column(UTCEnforcedDateTime, nullable = False)
  40.     last_login = Column(UTCEnforcedDateTime, nullable = True)
  41.     #<snip>
  42.  
  43. #Nasty hack (?) is here!
  44. utcConversionList = ["creation_date", "last_login"]
  45. User._EnsureUTC.__dict__["__sa_validators__"] = utcConversionList
Advertisement
Add Comment
Please, Sign In to add comment