Gráficas de compras por mes y año
[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 Purchase(Base):
14     __tablename__ = 'purchase'
15
16     id = Column(Integer, primary_key=True)
17     cost = Column(Numeric)
18     atime = Column(DateTime(), nullable=False, default=datetime.now)
19     items = Column(String(1024), default="")
20
21     def __init__(self, cost, items):
22         self.cost = cost
23         self.items = "|".join(items)
24
25     def getitems(self):
26         return ", ".join(self.items.split("|"))
27
28
29 class Item(Base):
30     __tablename__ = 'item'
31
32     name = Column(String(128), primary_key=True)
33     atime = Column(DateTime(), nullable=False, default=datetime.now)
34     tobuy = Column(Boolean, default=True)
35
36     def __init__(self, name):
37         self.name = name
38
39 class User(Base):
40     __tablename__ = 'users'
41
42     name = Column(String(60), primary_key=True)
43     password = Column(String(128))
44
45     def __init__(self, name, password):
46         self.name = unicode(name)
47         self.password = unicode(sha(password).hexdigest())
48
49     def set_password(self, password):
50         self.password = unicode(sha(password).hexdigest())
51
52     def auth(self, password):
53         return self.password == sha(password).hexdigest()
54
55     def __unicode__(self):
56         return '<User "%s">' % self.name
57
58 def connect(database='sqlite:///database.sqlite'):
59     db = create_engine(database, echo=False)
60     session = scoped_session(sessionmaker(bind=db))
61     return session
62
63 def create(database='sqlite:///database.sqlite'):
64     db = create_engine(database, echo=False)
65     metadata.create_all(db)
66
67 if __name__ == '__main__':
68     create()
69