|
| 1 | +import datetime |
| 2 | +from sqlalchemy import ( |
| 3 | + Column, |
| 4 | + DateTime, |
| 5 | + Index, |
| 6 | + Integer, |
| 7 | + Text, |
| 8 | + Unicode, |
| 9 | + UnicodeText, |
| 10 | + ) |
| 11 | + |
| 12 | +# from cryptacular.pbkdf2 import PBKDF2PassordManager as Manager |
| 13 | +from cryptacular.bcrypt import BCRYPTPasswordManager as Manager |
| 14 | + |
| 15 | +import sqlalchemy as sa |
| 16 | +from sqlalchemy.ext.declarative import declarative_base |
| 17 | + |
| 18 | +from sqlalchemy.orm import ( |
| 19 | + scoped_session, |
| 20 | + sessionmaker, |
| 21 | + ) |
| 22 | + |
| 23 | +from zope.sqlalchemy import ZopeTransactionExtension |
| 24 | + |
| 25 | +DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) |
| 26 | +Base = declarative_base() |
| 27 | + |
| 28 | + |
| 29 | +class MyModel(Base): |
| 30 | + __tablename__ = 'models' |
| 31 | + id = Column(Integer, primary_key=True) |
| 32 | + name = Column(Text) |
| 33 | + value = Column(Integer) |
| 34 | + |
| 35 | +Index('my_index', MyModel.name, unique=True, mysql_length=255) |
| 36 | + |
| 37 | + |
| 38 | +class Entry(Base): |
| 39 | + __tablename__ = 'entries' |
| 40 | + id = Column(Integer, primary_key=True) |
| 41 | + title = Column(Unicode(255), unique=True, nullable=False) |
| 42 | + body = Column(UnicodeText, default=u'') |
| 43 | + created = Column(DateTime, default=datetime.datetime.utcnow) |
| 44 | + edited = Column(DateTime, default=datetime.datetime.utcnow) |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def all(cls, session=None): |
| 48 | + """return a query with all entries, ordered by creation date reversed |
| 49 | + """ |
| 50 | + if session is None: |
| 51 | + session = DBSession |
| 52 | + return session.query(cls).order_by(sa.desc(cls.created)).all() |
| 53 | + |
| 54 | + @classmethod |
| 55 | + def by_id(cls, id, session=None): |
| 56 | + """return a single entry identified by id |
| 57 | +
|
| 58 | + If no entry exists with the provided id, return None |
| 59 | + """ |
| 60 | + if session is None: |
| 61 | + session = DBSession |
| 62 | + return session.query(cls).get(id) |
| 63 | + |
| 64 | + |
| 65 | +class User(Base): |
| 66 | + __tablename__ = 'users' |
| 67 | + id = Column(Integer, primary_key=True, autoincrement=True) |
| 68 | + name = Column(Unicode(255), unique=True, nullable=False) |
| 69 | + password = Column(Unicode(255), nullable=False) |
| 70 | + |
| 71 | + @classmethod |
| 72 | + def by_name(cls, name, session=None): |
| 73 | + if session is None: |
| 74 | + session = DBSession |
| 75 | + return DBSession.query(User).filter(User.name == name).first() |
| 76 | + |
| 77 | + def verify_password(self, password): |
| 78 | + manager = Manager() |
| 79 | + return manager.check(self.password, password) |
0 commit comments