|
| 1 | +import datetime |
| 2 | +from sqlalchemy import ( |
| 3 | + Column, |
| 4 | + DateTime, |
| 5 | + Index, |
| 6 | + Integer, |
| 7 | + Text, |
| 8 | + Unicode, |
| 9 | + UnicodeText, |
| 10 | + ) |
| 11 | + |
| 12 | +import sqlalchemy as sa |
| 13 | +from sqlalchemy.ext.declarative import declarative_base |
| 14 | + |
| 15 | +from sqlalchemy.orm import ( |
| 16 | + scoped_session, |
| 17 | + sessionmaker, |
| 18 | + ) |
| 19 | + |
| 20 | +from zope.sqlalchemy import ZopeTransactionExtension |
| 21 | + |
| 22 | +DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) |
| 23 | +Base = declarative_base() |
| 24 | + |
| 25 | + |
| 26 | +class MyModel(Base): |
| 27 | + __tablename__ = 'models' |
| 28 | + id = Column(Integer, primary_key=True) |
| 29 | + name = Column(Text) |
| 30 | + value = Column(Integer) |
| 31 | + |
| 32 | +Index('my_index', MyModel.name, unique=True, mysql_length=255) |
| 33 | + |
| 34 | + |
| 35 | +class Entry(Base): |
| 36 | + __tablename__ = 'entries' |
| 37 | + id = Column(Integer, primary_key=True) |
| 38 | + title = Column(Unicode(255), unique=True, nullable=False) |
| 39 | + body = Column(UnicodeText, default=u'') |
| 40 | + created = Column(DateTime, default=datetime.datetime.utcnow) |
| 41 | + edited = Column(DateTime, default=datetime.datetime.utcnow) |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def all(cls): |
| 45 | + """return a query with all entries, ordered by creation date reversed |
| 46 | + """ |
| 47 | + return DBSession.query(cls).order_by(sa.desc(cls.created)).all() |
| 48 | + |
| 49 | + @classmethod |
| 50 | + def by_id(cls, id): |
| 51 | + """return a single entry identified by id |
| 52 | +
|
| 53 | + If no entry exists with the provided id, return None |
| 54 | + """ |
| 55 | + return DBSession.query(cls).get(id) |
0 commit comments