version inicial de la aplicacion de gestion de compras
[compra.git] / db.py
1 #!/usr/bin/python
2
3 from sqlalchemy import *
4 from sqlalchemy.ext.declarative import declarative_base
5 from sqlalchemy.orm import sessionmaker, scoped_session
6
7 from datetime import datetime
8 from hashlib import sha256 as sha
9
10 Base = declarative_base()
11 metadata = Base.metadata
12
13 class Item(Base):
14     __tablename__ = 'item'
15
16     name = Column(String(128), primary_key=True)
17     atime = Column(DateTime(), nullable=False, default=datetime.now)
18     tobuy = Column(Boolean, default=True)
19
20     def __init__(self, name):
21         self.name = name
22
23 class User(Base):
24     __tablename__ = 'users'
25
26     name = Column(String(60), primary_key=True)
27     password = Column(String(128))
28
29     def __init__(self, name, password):
30         self.name = unicode(name)
31         self.password = unicode(sha(password).hexdigest())
32
33     def set_password(self, password):
34         self.password = unicode(sha(password).hexdigest())
35
36     def auth(self, password):
37         return self.password == sha(password).hexdigest()
38
39     def __unicode__(self):
40         return '<User "%s">' % self.name
41
42 def connect(database='sqlite:///database.sqlite'):
43     db = create_engine(database, echo=False)
44     session = scoped_session(sessionmaker(bind=db))
45     return session
46
47 def create(database='sqlite:///database.sqlite'):
48     db = create_engine(database, echo=False)
49     metadata.create_all(db)
50
51 if __name__ == '__main__':
52     create()
53