-
Notifications
You must be signed in to change notification settings - Fork 8
/
db.py
79 lines (65 loc) · 2.11 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import logging
log = logging.getLogger("db")
import os
from datetime import datetime
import sqlite3
import config
conn = sqlite3.connect(os.path.join('db', config.DB_FILE), isolation_level=None)
c = conn.cursor()
class Db:
def __init__(self, coin):
self.coin = coin
@classmethod
def create_tables(cls):
try:
c.execute("""
CREATE TABLE coinday
(
coin text,
day text,
btc real,
usd real,
supply real,
subs integer,
flw integer,
asubs integer,
PRIMARY KEY (coin, day)
)
""")
log.info("Database table `coinday` created")
except sqlite3.OperationalError as e:
log.warning(e)
try:
c.execute("""
ALTER TABLE coinday
ADD asubs integer
""")
log.info("Added field `coinday.asubs` - active subscribers")
except sqlite3.OperationalError as e:
log.warning(e)
def write_data(self, d):
try:
day = d["day"]
if isinstance(day, datetime):
day = day.strftime("%Y-%m-%d")
c.execute("""
insert into coinday values (?, ?, ?, ?, ?, ?, ?, ?)
""", (
self.coin,
day,
d.get("btc", None),
d.get("usd", None),
d.get("supply", None),
d.get("subs", None),
d.get("flw", None),
d.get("asubs", None),
))
return True
except sqlite3.IntegrityError:
return False
def get_series(self, s):
c.execute(f"select day, {s} from coinday where coin = ?", (self.coin,))
return [(datetime.strptime(k, "%Y-%m-%d"), v) for k,v in c.fetchall() if v is not None]
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
Db.create_tables()