import sqlalchemy as sa import sqlalchemy orm as orm import logging lo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import sqlalchemy as sa
import sqlalchemy.orm as orm
import logging
logging.basicConfig(level=logging.INFO)
meta = sa.MetaData()
realties = sa.Table('realties', meta,
sa.Column('id', sa.Integer, primary_key=True),
sa.Column('type', sa.String(50)),
sa.Column('owner', sa.String(200)),
sa.Column('area', sa.Float),
sa.Column('ceiling_height', sa.Float),
sa.Column('storeys_number', sa.Integer)
)
class Base(object):
def __init__(self, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
def __str__(self):
return "%s %s" % (self.__class__.__name__, id(self))
def __repr__(self):
return "<%s>" % self.__str__()
class RealtyObject(Base):
pass
class Structure(RealtyObject):
pass
class Building(Structure):
pass
class Room(Structure):
pass
Session = orm.scoped_session(orm.sessionmaker(autoflush=False))
realty_mapper = Session.mapper(RealtyObject, realties,
polymorphic_on=realties.c.type,
polymorphic_identity='realty',
exclude_properties=['storeys_number', 'ceiling_height'])
structure_mapper = Session.mapper(Structure,
inherits=realty_mapper,
polymorphic_identity='structure',
exclude_properties=['ceiling_height'])
building_mapper = Session.mapper(Building,
inherits=structure_mapper,
polymorphic_identity='building')
room_mapper = Session.mapper(Room,
inherits=structure_mapper,
polymorphic_identity='room',
exclude_properties=['storeys_number'])
def create_sample_data():
ins = realties.insert()
ins.execute([
{'id': 1, 'type': 'realty', 'owner': 'PooH', 'area': 1280.3},
{'id': 2, 'type': 'structure', 'owner': 'j2a', 'area': 300.0},
{'id': 3, 'type': 'building', 'owner': 'PooH', 'area': 120.0, 'storeys_number': 3},
{'id': 4, 'type': 'room', 'owner': 'PooH', 'area': 12.0, 'ceiling_height': 2.7},
{'id': 5, 'type': 'room', 'owner': 'j2a', 'area': 10.5, 'ceiling_height': 2.7},
])
def make_engine():
engine = sa.create_engine('sqlite:///rlt.db')
Session.configure(bind=engine)
meta.bind = engine
meta.create_all()
return engine