AƱadido sistema simple de login
[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         self.password = unicode(sha(password).hexdigest())
29
30     def auth(self, password):
31         return self.password == sha(password).hexdigest()
32
33     def __unicode__(self):
34         return '<User "%s">' % self.name
35
36 def connect(database='sqlite:///database.sqlite'):
37     db = create_engine(database, echo=False)
38     session = scoped_session(sessionmaker(bind=db))
39     return session
40
41 def create(database='sqlite:///database.sqlite'):
42     db = create_engine(database, echo=False)
43     metadata.create_all(db)
44
45 if __name__ == '__main__':
46     create()
47