Created
September 20, 2012 17:36
-
-
Save Tefnet/3757273 to your computer and use it in GitHub Desktop.
How to avoid monkey-patching sqlalchemy.ext.declarative.api._as_declarative
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
import sqlalchemy as sa | |
import sqlalchemy.ext.declarative | |
""" | |
How to avoid monkey-patching sqlalchemy.ext.declarative.api._as_declarative??? | |
""" | |
USE_EVENT=True | |
if USE_EVENT: | |
@sa.event.listens_for(sa.orm.mapper, "mapper_configured") | |
def _setup_tefproperties(mapper, class_): | |
for key, value in class_.__dict__.items(): | |
if isinstance(value, TefProperty): | |
value._config(class_, key) | |
else: | |
_as_declarative_orig = sqlalchemy.ext.declarative.api._as_declarative | |
def _as_declarative_tef(cls, classname, dict_): | |
dict_ = dict(dict_) | |
for key, value in cls.__dict__.items(): | |
if isinstance(value, TefProperty): | |
dict_[key] = value._config(cls, key) | |
return _as_declarative_orig(cls, classname, dict_) | |
sqlalchemy.ext.declarative.api._as_declarative = _as_declarative_tef | |
Base = sqlalchemy.ext.declarative.declarative_base(mapper=sa.orm.mapper) | |
engine = sa.create_engine('sqlite:///:memory:', echo = True) | |
class TefProperty(object): | |
def _config(self, cls, key): | |
col = sa.Column(key, self.sqla_type) | |
setattr(cls, key, col) | |
return col | |
class propInt(TefProperty): | |
sqla_type = sa.types.Integer | |
class propStr(TefProperty): | |
sqla_type = sa.types.String | |
class Foo(Base): | |
__tablename__ = 'foo' | |
id = sa.Column( sa.types.Integer, primary_key=True) | |
intprop = propInt() | |
strprop = propStr() | |
Base.metadata.create_all(engine, checkfirst=True) | |
Session = sa.orm.sessionmaker( | |
bind = engine, | |
autocommit = False, | |
) | |
session = Session() | |
session.query(Foo).filter(Foo.intprop + Foo.intprop, Foo.strprop + Foo.strprop).all() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://groups.google.com/d/topic/sqlalchemy/G2jC0tn-EX8/discussion