-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.py
142 lines (102 loc) · 3.95 KB
/
api.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import os
import json
import datetime
from datetime import timezone
import pymongo
from flask import Flask, jsonify, request
from bson.objectid import ObjectId
from flask.helpers import make_response
from config import setup_logging, setup_db
from lib import TimeFormat
import smartMe
logger = setup_logging()
db = setup_db()
log_collection = db.log
time_before_2nd_panel = datetime.datetime(year=2016, month=3, day=18)
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
elif isinstance(o, datetime.datetime):
return o.strftime(TimeFormat)
return json.JSONEncoder.default(self, o)
class InvalidAPIUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
app = Flask(__name__)
@app.errorhandler(InvalidAPIUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/')
def index():
return app.send_static_file('index.html')
@app.route('/smartMeImport', methods=['POST'])
def route_import():
client_data = request.get_json(force=True)
dates_from_to = smartMe.import_data(client_data['username'], client_data['password'], client_data['deviceId'], log_collection)
return jsonify({'error': None, 'importFromTo': dates_from_to})
@app.route('/data/<device_id>/years')
def data_years(device_id):
return get_data(device_id, "%Y")
@app.route('/data/<device_id>/months')
def data_months(device_id):
return get_data(device_id, "%Y-%m")
@app.route('/data/<device_id>/weeks')
def data_weeks(device_id):
return get_data(device_id, "%Y-%U")
@app.route('/data/<device_id>/days')
def data_days(device_id):
return get_data(device_id, "%Y-%m-%d")
@app.route('/data/<device_id>/hours')
def data_hours(device_id):
return get_data(device_id, "%Y-%m-%d %H")
def get_data(device_id, aggregation_date_format):
def create_item(c):
t = c['_id']
watt_hours = c['wattHours']
#if t < time_before_2nd_panel:
# watt_hours = watt_hours * 2
return {'time': t, 'wattHours': watt_hours}
return jsonify([create_item(c) for c in log_collection.aggregate([
{'$match': {'deviceId': device_id}},
{'$project': {'date': {'$dateToString': {'format': aggregation_date_format, 'date': "$time"}}, 'wattHours': '$wattHours'}},
{'$group': {'_id': '$date', 'wattHours': {'$sum': '$wattHours'}}},
{'$sort': {'_id': pymongo.DESCENDING}},
{'$limit': 50},
{'$sort': {'_id': pymongo.ASCENDING}},
])])
@app.route('/metrics')
def metrics():
existing_entry = log_collection.find_one(sort=[('updatedAt', pymongo.DESCENDING), ])
if existing_entry:
updated_at = existing_entry['updatedAt'].replace(tzinfo=timezone.utc).timestamp()
else:
updated_at = None
week_ago = datetime.datetime.utcnow() - datetime.timedelta(days=7)
results = list(map(lambda r: 'production_past_7days{deviceId="' + r['_id'] + '"} ' + str(-r['wattHours']),
log_collection.aggregate([
{'$match': {'time': {'$gt': week_ago}}},
{'$group': {'_id': '$deviceId', 'wattHours': {'$sum': '$wattHours'}}},
]
)
)
)
results.append('updated_at ' + str(updated_at))
response = make_response("\n".join(results) + "\n")
response.headers["content-type"] = "text/plain"
return response
app.json_encoder = JSONEncoder
if __name__ == "__main__":
port = int(os.getenv("VCAP_APP_PORT", "5000"))
app.run(port=port)