Advertisement
Guest User

Untitled

a guest
Feb 4th, 2012
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. from sqlalchemy import create_engine, Column, Integer
  2. from sqlalchemy.ext.declarative import declarative_base, declared_attr
  3. from sqlalchemy.orm import sessionmaker
  4.  
  5. import settings
  6.  
  7.  
  8. engine = create_engine(settings.connection_uri)
  9. BaseSession = sessionmaker(bind=engine)
  10.  
  11.  
  12. class Singleton(type):
  13.  
  14.     def __init__(cls, *args, **kwargs):
  15.         super(Singleton, cls).__init__(*args, **kwargs)
  16.         cls.instance = None
  17.  
  18.     def __call__(cls, *args, **kwargs):
  19.         if cls.instance is None:
  20.             cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
  21.         return cls.instance
  22.  
  23.  
  24. class Session(BaseSession):
  25.  
  26.     __metaclass__ = Singleton
  27.  
  28.  
  29. class Base(object):
  30.  
  31.     @declared_attr
  32.     def __tablename__(cls):
  33.         return cls.__name__
  34.  
  35.     session = Session()
  36.     id = Column(Integer, primary_key=True)
  37.  
  38.     def save(self):
  39.         self.session.add(self)
  40.         self.session.commit()
  41.  
  42.  
  43. Base = declarative_base(cls=Base)
  44.  
  45.  
  46. class TestTable(Base):
  47.  
  48.     pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement