Skip to content

Instantly share code, notes, and snippets.

@hirose31

hirose31/athanor.py

Created Oct 16, 2018
Embed
What would you like to do?
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlathanor import declarative_base, Column, relationship
from sqlalchemy import create_engine, Integer, String, Sequence, ForeignKey
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
def serialize_address(input):
raise RuntimeError('oops')
return input
class User(Base):
__tablename__ = 'users'
id = Column(Integer,
Sequence('user_id_seq'),
primary_key=True,
supports_dict=True,
)
name = Column(String,
supports_dict=True,
)
addresses = relationship("Address",
backref="user",
lazy="joined",
supports_dict=True,
on_serialize=serialize_address,
)
def __repr__(self):
return "<User(id='{0:s}', name='{1:s}')>".format(
str(self.id),
self.name,
)
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer,
primary_key=True,
supports_dict=True,
)
email = Column(String,
nullable=False,
supports_dict=True,
)
user_id = Column(Integer,
ForeignKey('users.id'),
supports_dict=True,
)
def __repr__(self):
return "<Address(email='{0:s}')>".format(
self.email,
)
def main():
engine = create_engine('sqlite:///athanor.db',
# echo=True,
)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
scott = User(name='scott')
scott.addresses = [
Address(email='scott@example.com'),
Address(email='scott@example.org'),
]
session.add(scott)
session.commit()
print(scott.to_dict(max_nesting=2))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment