Skip to content

Instantly share code, notes, and snippets.

@hirose31
Created October 16, 2018 04:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirose31/b9d8843e473508daa465659880a9285c to your computer and use it in GitHub Desktop.
Save hirose31/b9d8843e473508daa465659880a9285c to your computer and use it in GitHub Desktop.
#!/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