aƱadido metodo set_password
[webpysample.git] / db.py
1 from sqlalchemy import *
2 from sqlalchemy.ext.declarative import declarative_base
3 from sqlalchemy.orm import sessionmaker, scoped_session
4
5 from hashlib import sha256 as sha
6
7 Base = declarative_base()
8 metadata = Base.metadata
9
10 class Test(Base):
11     __tablename__ = 'test'
12
13     id = Column(Integer, primary_key=True)
14     test = Column(String(128))
15     atime = Column(DateTime(), nullable=False, server_default=text('current_timestamp'))
16
17     def __init__(self, test):
18         self.test = test
19
20 class User(Base):
21     __tablename__ = 'users'
22
23     name = Column(String(60), primary_key=True)
24     password = Column(String(128))
25
26     def __init__(self, name, password):
27         self.name = unicode(name)
28         set_password(password)
29
30     def set_password(self, password):
31         self.password = unicode(sha(password).hexdigest())
32
33     def auth(self, password):
34         return self.password == sha(password).hexdigest()
35
36     def __unicode__(self):
37         return '<User "%s">' % self.name
38
39 def connect(database='sqlite:///database.sqlite'):
40     db = create_engine(database, echo=False)
41     session = scoped_session(sessionmaker(bind=db))
42     return session
43
44 def create(database='sqlite:///database.sqlite'):
45     db = create_engine(database, echo=False)
46     metadata.create_all(db)
47
48 if __name__ == '__main__':
49     create()
50