Created
March 23, 2012 18:30
-
-
Save major/2173517 to your computer and use it in GitHub Desktop.
Easy representation of data object in SQLAlchemy with BaseExt
This file contains hidden or 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
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/[email protected]/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