-
Notifications
You must be signed in to change notification settings - Fork 0
/
koodo.py
127 lines (103 loc) · 3.46 KB
/
koodo.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#!/usr/bin/env python
import sys
import time
import json
import datetime
from flask import Flask, render_template, Response
from sqlalchemy import asc
from scraper import Scraper
from database import db_session, UsageDataPoint, KoodoTransaction
from credentials import get_creds
app = Flask(__name__)
app.debug = True
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
@app.route("/usage.csv")
def usage_csv():
entries = UsageDataPoint.query.order_by(asc(UsageDataPoint.time)).all()
header = "time,min,mb"
rows = [
','.join([
str(e.time.strftime('%s')),
str(e.minutes_remaining),
str(e.mb_remaining),
]) for e in entries
]
return Response("\n".join([header] + rows), mimetype='text/csv')
@app.route("/usage.json")
def usage_json():
entries = UsageDataPoint.query.order_by(asc(UsageDataPoint.time)).all()
return Response(
json.dumps([x.to_object() for x in entries]),
mimetype='application/json'
)
@app.route("/transactions.csv")
def transactions_csv():
entries = KoodoTransaction.query.order_by(asc(KoodoTransaction.date)).all()
header = "date,description,credit,debit"
rows = [
','.join([
unicode(e.date.strftime('%s')),
unicode(e.description),
unicode(e.credit),
unicode(e.debit),
]) for e in entries
]
return Response("\n".join([header] + rows), mimetype='text/csv')
@app.route("/transactions.json")
def transactions_json():
entries = KoodoTransaction.query.order_by(asc(KoodoTransaction.date)).all()
time_period = datetime.datetime.utcnow().date() - entries[0].date
total_seconds = time_period.total_seconds()
total_months = total_seconds / (30 * 24 * 60 * 60.)
total_paid = sum([(x.credit or 0) for x in entries])
response = {
"transactions": [x.to_object() for x in entries],
"balance": sum([(x.credit or 0) - (x.debit or 0) for x in entries]),
"total_paid": total_paid,
"total_used": sum([(x.debit or 0) for x in entries]),
"number_months": total_months,
"avg_monthly_cost": total_paid / total_months,
}
return Response(
json.dumps(response),
mimetype='application/json'
)
@app.route("/")
def index():
return render_template('index.html')
def scrape():
scraper = Scraper(**get_creds())
# Fetch usage info re: boosters.
le = UsageDataPoint(
time=datetime.datetime.utcnow(),
**scraper.fetch_booster_usage()
)
db_session.add(le)
yield le
# Fetch latest transactions and put these in the DB,
# but only if we don't already have them.
for transaction in scraper.fetch_most_recent_transactions():
existing = KoodoTransaction \
.query \
.filter_by(koodo_id=transaction['koodo_id']) \
.first()
if not existing:
kt = KoodoTransaction(**transaction)
db_session.add(kt)
yield kt
db_session.commit()
if __name__ == "__main__":
if ('--fetch' in sys.argv or
(sys.stdout.isatty() and '--server' not in sys.argv)):
start_time = time.time()
print "Fetching latest data from Koodo..."
for row in scrape():
print dict(row.to_object())
end_time = time.time()
print "Done fetching. (Took %2.2f msec.)" % (
(end_time - start_time) * 1000
)
else:
app.run()