Created
March 13, 2014 21:26
-
-
Save kanzure/9537310 to your computer and use it in GitHub Desktop.
sqlalchemy type coercion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Type coercion for sqlalchemy prior to committing to some database. | |
http://stackoverflow.com/questions/8980735/how-can-i-verify-column-data-types-in-the-sqlalchemy-orm | |
""" | |
from sqlalchemy import ( | |
Column, | |
Integer, | |
String, | |
DateTime, | |
) | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy import event | |
import datetime | |
Base = declarative_base() | |
type_coercion = { | |
Integer: int, | |
String: str, | |
DateTime: datetime.datetime, | |
} | |
# this event is called whenever an attribute | |
# on a class is instrumented | |
@event.listens_for(Base, 'attribute_instrument') | |
def configure_listener(class_, key, inst): | |
if not hasattr(inst.property, 'columns'): | |
return | |
# this event is called whenever a "set" | |
# occurs on that instrumented attribute | |
@event.listens_for(inst, "set", retval=True) | |
def set_(instance, value, oldvalue, initiator): | |
desired_type = type_coercion.get(inst.property.columns[0].type.__class__) | |
coerced_value = desired_type(value) | |
return coerced_value | |
class MyObject(Base): | |
__tablename__ = 'mytable' | |
id = Column(Integer, primary_key=True) | |
svalue = Column(String) | |
ivalue = Column(Integer) | |
dvalue = Column(DateTime) | |
x = MyObject(svalue=50) | |
assert isinstance(x.svalue, str) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment