Skip to content

Instantly share code, notes, and snippets.

@major
Created March 23, 2012 18:30
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 major/2173517 to your computer and use it in GitHub Desktop.
Save major/2173517 to your computer and use it in GitHub Desktop.
Easy representation of data object in SQLAlchemy with BaseExt
from sqlalchemy import create_engine, Table, Column, Integer, ForeignKey, String, DateTime
from sqlalchemy.orm import relationship, backref, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://user:pass@localhost/databasename')
# Found: http://www.mail-archive.com/sqlalchemy@googlegroups.com/msg18049.html
class BaseExt(object):
"""Does much nicer repr/print of class instances
from sqlalchemy list suggested by Michael Bayer
"""
def __repr__(self):
return "%s(%s)" % (
(self.__class__.__name__),
', '.join(["%s=%r" % (key, getattr(self, key))
for key in sorted(self.__dict__.keys())
if not key.startswith('_')]))
Base = declarative_base(cls=BaseExt)
# Declare tables as usual...
class Packages(Base):
__tablename__ = 'hosts'
id = Column(Integer, primary_key=True)
name = Column(String(250))
version = Column(String(250))
arch = Column(String(20))
Session = sessionmaker(bind=engine)
session = Session()
for package in session.query(Packages).all():
print package
# Before: <__main__.Packages object at 0x2895ed0>
# After: Packages(arch='amd64', host_id=1L, id=1L, name='apache2', version='2.2')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment