Total Complexity | 292 |
Total Lines | 1563 |
Duplicated Lines | 61.42 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like core.tenant often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import falcon |
||
2 | import simplejson as json |
||
3 | import mysql.connector |
||
4 | import config |
||
5 | import uuid |
||
6 | from datetime import datetime, timedelta, timezone |
||
7 | |||
8 | |||
9 | class TenantCollection: |
||
10 | @staticmethod |
||
11 | def __init__(): |
||
12 | pass |
||
13 | |||
14 | @staticmethod |
||
15 | def on_options(req, resp): |
||
16 | resp.status = falcon.HTTP_200 |
||
17 | |||
18 | @staticmethod |
||
19 | def on_get(req, resp): |
||
20 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
21 | cursor = cnx.cursor(dictionary=True) |
||
22 | |||
23 | query = (" SELECT id, name, uuid " |
||
24 | " FROM tbl_tenant_types ") |
||
25 | cursor.execute(query) |
||
26 | rows_tenant_types = cursor.fetchall() |
||
27 | |||
28 | tenant_type_dict = dict() |
||
29 | if rows_tenant_types is not None and len(rows_tenant_types) > 0: |
||
30 | for row in rows_tenant_types: |
||
31 | tenant_type_dict[row['id']] = {"id": row['id'], |
||
32 | "name": row['name'], |
||
33 | "uuid": row['uuid']} |
||
34 | |||
35 | query = (" SELECT id, name, uuid " |
||
36 | " FROM tbl_contacts ") |
||
37 | cursor.execute(query) |
||
38 | rows_contacts = cursor.fetchall() |
||
39 | |||
40 | contact_dict = dict() |
||
41 | if rows_contacts is not None and len(rows_contacts) > 0: |
||
42 | for row in rows_contacts: |
||
43 | contact_dict[row['id']] = {"id": row['id'], |
||
44 | "name": row['name'], |
||
45 | "uuid": row['uuid']} |
||
46 | |||
47 | query = (" SELECT id, name, uuid " |
||
48 | " FROM tbl_cost_centers ") |
||
49 | cursor.execute(query) |
||
50 | rows_cost_centers = cursor.fetchall() |
||
51 | |||
52 | cost_center_dict = dict() |
||
53 | if rows_cost_centers is not None and len(rows_cost_centers) > 0: |
||
54 | for row in rows_cost_centers: |
||
55 | cost_center_dict[row['id']] = {"id": row['id'], |
||
56 | "name": row['name'], |
||
57 | "uuid": row['uuid']} |
||
58 | |||
59 | query = (" SELECT id, name, uuid, " |
||
60 | " buildings, floors, rooms, area, tenant_type_id, " |
||
61 | " is_input_counted, is_key_tenant, " |
||
62 | " lease_number, lease_start_datetime_utc, lease_end_datetime_utc, is_in_lease, " |
||
63 | " contact_id, cost_center_id, description " |
||
64 | " FROM tbl_tenants " |
||
65 | " ORDER BY id ") |
||
66 | cursor.execute(query) |
||
67 | rows_spaces = cursor.fetchall() |
||
68 | |||
69 | result = list() |
||
70 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
71 | for row in rows_spaces: |
||
72 | tenant_type = tenant_type_dict.get(row['tenant_type_id'], None) |
||
73 | contact = contact_dict.get(row['contact_id'], None) |
||
74 | cost_center = cost_center_dict.get(row['cost_center_id'], None) |
||
75 | |||
76 | lease_start_datetime_utc = row['lease_start_datetime_utc'].replace(tzinfo=timezone.utc) |
||
77 | lease_end_datetime_utc = row['lease_end_datetime_utc'].replace(tzinfo=timezone.utc) |
||
78 | |||
79 | meta_result = {"id": row['id'], |
||
80 | "name": row['name'], |
||
81 | "uuid": row['uuid'], |
||
82 | "buildings": row['buildings'], |
||
83 | "floors": row['floors'], |
||
84 | "rooms": row['rooms'], |
||
85 | "area": row['area'], |
||
86 | "tenant_type": tenant_type, |
||
87 | "is_input_counted": bool(row['is_input_counted']), |
||
88 | "is_key_tenant": bool(row['is_key_tenant']), |
||
89 | "lease_number": row['lease_number'], |
||
90 | "lease_start_datetime_utc": lease_start_datetime_utc.timestamp() * 1000, |
||
91 | "lease_end_datetime_utc": lease_end_datetime_utc.timestamp() * 1000, |
||
92 | "is_in_lease": bool(row['is_in_lease']), |
||
93 | "contact": contact, |
||
94 | "cost_center": cost_center, |
||
95 | "description": row['description']} |
||
96 | result.append(meta_result) |
||
97 | |||
98 | cursor.close() |
||
99 | cnx.disconnect() |
||
100 | resp.body = json.dumps(result) |
||
101 | |||
102 | @staticmethod |
||
103 | def on_post(req, resp): |
||
104 | """Handles POST requests""" |
||
105 | try: |
||
106 | raw_json = req.stream.read().decode('utf-8') |
||
107 | except Exception as ex: |
||
108 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
109 | |||
110 | new_values = json.loads(raw_json) |
||
111 | |||
112 | if 'name' not in new_values['data'].keys() or \ |
||
113 | not isinstance(new_values['data']['name'], str) or \ |
||
114 | len(str.strip(new_values['data']['name'])) == 0: |
||
115 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
116 | description='API.INVALID_TENANT_NAME') |
||
117 | name = str.strip(new_values['data']['name']) |
||
118 | |||
119 | if 'buildings' not in new_values['data'].keys() or \ |
||
120 | not isinstance(new_values['data']['buildings'], str) or \ |
||
121 | len(str.strip(new_values['data']['buildings'])) == 0: |
||
122 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
123 | description='API.INVALID_BUILDINGS_VALUE') |
||
124 | buildings = str.strip(new_values['data']['buildings']) |
||
125 | |||
126 | if 'floors' not in new_values['data'].keys() or \ |
||
127 | not isinstance(new_values['data']['floors'], str) or \ |
||
128 | len(str.strip(new_values['data']['floors'])) == 0: |
||
129 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
130 | description='API.INVALID_FLOORS_VALUE') |
||
131 | floors = str.strip(new_values['data']['floors']) |
||
132 | |||
133 | if 'rooms' not in new_values['data'].keys() or \ |
||
134 | not isinstance(new_values['data']['rooms'], str) or \ |
||
135 | len(str.strip(new_values['data']['rooms'])) == 0: |
||
136 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
137 | description='API.INVALID_ROOMS_VALUE') |
||
138 | rooms = str.strip(new_values['data']['rooms']) |
||
139 | |||
140 | if 'area' not in new_values['data'].keys() or \ |
||
141 | not (isinstance(new_values['data']['area'], float) or |
||
142 | isinstance(new_values['data']['area'], int)): |
||
143 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
144 | description='API.INVALID_AREA_VALUE') |
||
145 | area = new_values['data']['area'] |
||
146 | |||
147 | if 'tenant_type_id' not in new_values['data'].keys() or \ |
||
148 | not isinstance(new_values['data']['tenant_type_id'], int) or \ |
||
149 | new_values['data']['tenant_type_id'] <= 0: |
||
150 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
151 | description='API.INVALID_TENANT_TYPE_ID') |
||
152 | tenant_type_id = new_values['data']['tenant_type_id'] |
||
153 | |||
154 | if 'is_input_counted' not in new_values['data'].keys() or \ |
||
155 | not isinstance(new_values['data']['is_input_counted'], bool): |
||
156 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
157 | description='API.INVALID_IS_INPUT_COUNTED_VALUE') |
||
158 | is_input_counted = new_values['data']['is_input_counted'] |
||
159 | |||
160 | if 'is_key_tenant' not in new_values['data'].keys() or \ |
||
161 | not isinstance(new_values['data']['is_key_tenant'], bool): |
||
162 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
163 | description='API.INVALID_IS_KEY_TENANT_VALUE') |
||
164 | is_key_tenant = new_values['data']['is_key_tenant'] |
||
165 | |||
166 | if 'lease_number' not in new_values['data'].keys() or \ |
||
167 | not isinstance(new_values['data']['lease_number'], str) or \ |
||
168 | len(str.strip(new_values['data']['lease_number'])) == 0: |
||
169 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
170 | description='API.INVALID_LEASE_NUMBER_VALUE') |
||
171 | lease_number = str.strip(new_values['data']['lease_number']) |
||
172 | |||
173 | if 'is_in_lease' not in new_values['data'].keys() or \ |
||
174 | not isinstance(new_values['data']['is_in_lease'], bool): |
||
175 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
176 | description='API.INVALID_IS_IN_LEASE_VALUE') |
||
177 | is_in_lease = new_values['data']['is_in_lease'] |
||
178 | |||
179 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
180 | if config.utc_offset[0] == '-': |
||
181 | timezone_offset = -timezone_offset |
||
182 | |||
183 | # todo: validate datetime values |
||
184 | lease_start_datetime_utc = datetime.strptime(new_values['data']['lease_start_datetime_utc'], |
||
185 | '%Y-%m-%dT%H:%M:%S') |
||
186 | lease_start_datetime_utc = lease_start_datetime_utc.replace(tzinfo=timezone.utc) |
||
187 | lease_start_datetime_utc -= timedelta(minutes=timezone_offset) |
||
188 | |||
189 | lease_end_datetime_utc = datetime.strptime(new_values['data']['lease_end_datetime_utc'], |
||
190 | '%Y-%m-%dT%H:%M:%S') |
||
191 | lease_end_datetime_utc = lease_end_datetime_utc.replace(tzinfo=timezone.utc) |
||
192 | lease_end_datetime_utc -= timedelta(minutes=timezone_offset) |
||
193 | |||
194 | if 'contact_id' not in new_values['data'].keys() or \ |
||
195 | not isinstance(new_values['data']['contact_id'], int) or \ |
||
196 | new_values['data']['contact_id'] <= 0: |
||
197 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
198 | description='API.INVALID_CONTACT_ID') |
||
199 | contact_id = new_values['data']['contact_id'] |
||
200 | |||
201 | if 'cost_center_id' not in new_values['data'].keys() or \ |
||
202 | not isinstance(new_values['data']['cost_center_id'], int) or \ |
||
203 | new_values['data']['cost_center_id'] <= 0: |
||
204 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
205 | description='API.INVALID_COST_CENTER_ID') |
||
206 | cost_center_id = new_values['data']['cost_center_id'] |
||
207 | |||
208 | if 'description' in new_values['data'].keys() and \ |
||
209 | new_values['data']['description'] is not None and \ |
||
210 | len(str(new_values['data']['description'])) > 0: |
||
211 | description = str.strip(new_values['data']['description']) |
||
212 | else: |
||
213 | description = None |
||
214 | |||
215 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
216 | cursor = cnx.cursor() |
||
217 | |||
218 | cursor.execute(" SELECT name " |
||
219 | " FROM tbl_tenants " |
||
220 | " WHERE name = %s ", (name,)) |
||
221 | if cursor.fetchone() is not None: |
||
222 | cursor.close() |
||
223 | cnx.disconnect() |
||
224 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
225 | description='API.TENANT_NAME_IS_ALREADY_IN_USE') |
||
226 | |||
227 | cursor.execute(" SELECT name " |
||
228 | " FROM tbl_tenant_types " |
||
229 | " WHERE id = %s ", |
||
230 | (tenant_type_id,)) |
||
231 | if cursor.fetchone() is None: |
||
232 | cursor.close() |
||
233 | cnx.disconnect() |
||
234 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
235 | description='API.TENANT_TYPE_NOT_FOUND') |
||
236 | |||
237 | cursor.execute(" SELECT name " |
||
238 | " FROM tbl_contacts " |
||
239 | " WHERE id = %s ", |
||
240 | (new_values['data']['contact_id'],)) |
||
241 | row = cursor.fetchone() |
||
242 | if row is None: |
||
243 | cursor.close() |
||
244 | cnx.disconnect() |
||
245 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
246 | description='API.CONTACT_NOT_FOUND') |
||
247 | |||
248 | cursor.execute(" SELECT name " |
||
249 | " FROM tbl_cost_centers " |
||
250 | " WHERE id = %s ", |
||
251 | (new_values['data']['cost_center_id'],)) |
||
252 | row = cursor.fetchone() |
||
253 | if row is None: |
||
254 | cursor.close() |
||
255 | cnx.disconnect() |
||
256 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
257 | description='API.COST_CENTER_NOT_FOUND') |
||
258 | |||
259 | add_values = (" INSERT INTO tbl_tenants " |
||
260 | " (name, uuid, buildings, floors, rooms, area, tenant_type_id, " |
||
261 | " is_input_counted, is_key_tenant, " |
||
262 | " lease_number, lease_start_datetime_utc, lease_end_datetime_utc, is_in_lease, " |
||
263 | " contact_id, cost_center_id, description) " |
||
264 | " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) ") |
||
265 | cursor.execute(add_values, (name, |
||
266 | str(uuid.uuid4()), |
||
267 | buildings, |
||
268 | floors, |
||
269 | rooms, |
||
270 | area, |
||
271 | tenant_type_id, |
||
272 | is_input_counted, |
||
273 | is_key_tenant, |
||
274 | lease_number, |
||
275 | lease_start_datetime_utc, |
||
276 | lease_end_datetime_utc, |
||
277 | is_in_lease, |
||
278 | contact_id, |
||
279 | cost_center_id, |
||
280 | description)) |
||
281 | new_id = cursor.lastrowid |
||
282 | cnx.commit() |
||
283 | cursor.close() |
||
284 | cnx.disconnect() |
||
285 | |||
286 | resp.status = falcon.HTTP_201 |
||
287 | resp.location = '/tenants/' + str(new_id) |
||
288 | |||
289 | |||
290 | class TenantItem: |
||
291 | @staticmethod |
||
292 | def __init__(): |
||
293 | pass |
||
294 | |||
295 | @staticmethod |
||
296 | def on_options(req, resp, id_): |
||
297 | resp.status = falcon.HTTP_200 |
||
298 | |||
299 | @staticmethod |
||
300 | def on_get(req, resp, id_): |
||
301 | if not id_.isdigit() or int(id_) <= 0: |
||
302 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
303 | description='API.INVALID_TENANT_ID') |
||
304 | |||
305 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
306 | cursor = cnx.cursor(dictionary=True) |
||
307 | |||
308 | query = (" SELECT id, name, uuid " |
||
309 | " FROM tbl_tenant_types ") |
||
310 | cursor.execute(query) |
||
311 | rows_tenant_types = cursor.fetchall() |
||
312 | |||
313 | tenant_type_dict = dict() |
||
314 | if rows_tenant_types is not None and len(rows_tenant_types) > 0: |
||
315 | for row in rows_tenant_types: |
||
316 | tenant_type_dict[row['id']] = {"id": row['id'], |
||
317 | "name": row['name'], |
||
318 | "uuid": row['uuid']} |
||
319 | |||
320 | query = (" SELECT id, name, uuid " |
||
321 | " FROM tbl_contacts ") |
||
322 | cursor.execute(query) |
||
323 | rows_contacts = cursor.fetchall() |
||
324 | |||
325 | contact_dict = dict() |
||
326 | if rows_contacts is not None and len(rows_contacts) > 0: |
||
327 | for row in rows_contacts: |
||
328 | contact_dict[row['id']] = {"id": row['id'], |
||
329 | "name": row['name'], |
||
330 | "uuid": row['uuid']} |
||
331 | |||
332 | query = (" SELECT id, name, uuid " |
||
333 | " FROM tbl_cost_centers ") |
||
334 | cursor.execute(query) |
||
335 | rows_cost_centers = cursor.fetchall() |
||
336 | |||
337 | cost_center_dict = dict() |
||
338 | if rows_cost_centers is not None and len(rows_cost_centers) > 0: |
||
339 | for row in rows_cost_centers: |
||
340 | cost_center_dict[row['id']] = {"id": row['id'], |
||
341 | "name": row['name'], |
||
342 | "uuid": row['uuid']} |
||
343 | |||
344 | query = (" SELECT id, name, uuid, " |
||
345 | " buildings, floors, rooms, area, tenant_type_id," |
||
346 | " is_key_tenant, is_input_counted, " |
||
347 | " lease_number, lease_start_datetime_utc, lease_end_datetime_utc, is_in_lease, " |
||
348 | " contact_id, cost_center_id, description " |
||
349 | " FROM tbl_tenants " |
||
350 | " WHERE id = %s ") |
||
351 | cursor.execute(query, (id_,)) |
||
352 | row = cursor.fetchone() |
||
353 | cursor.close() |
||
354 | cnx.disconnect() |
||
355 | |||
356 | if row is None: |
||
357 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
358 | description='API.TENANT_NOT_FOUND') |
||
359 | else: |
||
360 | tenant_type = tenant_type_dict.get(row['tenant_type_id'], None) |
||
361 | contact = contact_dict.get(row['contact_id'], None) |
||
362 | cost_center = cost_center_dict.get(row['cost_center_id'], None) |
||
363 | meta_result = {"id": row['id'], |
||
364 | "name": row['name'], |
||
365 | "uuid": row['uuid'], |
||
366 | "buildings": row['buildings'], |
||
367 | "floors": row['floors'], |
||
368 | "rooms": row['rooms'], |
||
369 | "area": row['area'], |
||
370 | "tenant_type": tenant_type, |
||
371 | "is_input_counted": bool(row['is_input_counted']), |
||
372 | "is_key_tenant": bool(row['is_key_tenant']), |
||
373 | "lease_number": row['lease_number'], |
||
374 | "lease_start_datetime_utc": row['lease_start_datetime_utc'].timestamp() * 1000, |
||
375 | "lease_end_datetime_utc": row['lease_end_datetime_utc'].timestamp() * 1000, |
||
376 | "is_in_lease": bool(row['is_in_lease']), |
||
377 | "contact": contact, |
||
378 | "cost_center": cost_center, |
||
379 | "description": row['description']} |
||
380 | |||
381 | resp.body = json.dumps(meta_result) |
||
382 | |||
383 | View Code Duplication | @staticmethod |
|
|
|||
384 | def on_delete(req, resp, id_): |
||
385 | if not id_.isdigit() or int(id_) <= 0: |
||
386 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
387 | description='API.INVALID_TENANT_ID') |
||
388 | |||
389 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
390 | cursor = cnx.cursor() |
||
391 | |||
392 | cursor.execute(" SELECT name " |
||
393 | " FROM tbl_tenants " |
||
394 | " WHERE id = %s ", (id_,)) |
||
395 | if cursor.fetchone() is None: |
||
396 | cursor.close() |
||
397 | cnx.disconnect() |
||
398 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
399 | description='API.TENANT_NOT_FOUND') |
||
400 | |||
401 | # check relation with space |
||
402 | cursor.execute(" SELECT space_id " |
||
403 | " FROM tbl_spaces_tenants " |
||
404 | " WHERE tenant_id = %s ", |
||
405 | (id_,)) |
||
406 | rows_spaces = cursor.fetchall() |
||
407 | if rows_spaces is not None and len(rows_spaces) > 0: |
||
408 | cursor.close() |
||
409 | cnx.disconnect() |
||
410 | raise falcon.HTTPError(falcon.HTTP_400, |
||
411 | title='API.BAD_REQUEST', |
||
412 | description='API.THERE_IS_RELATION_WITH_SPACES') |
||
413 | |||
414 | # check relation with meter |
||
415 | cursor.execute(" SELECT meter_id " |
||
416 | " FROM tbl_tenants_meters " |
||
417 | " WHERE tenant_id = %s ", |
||
418 | (id_,)) |
||
419 | rows_meters = cursor.fetchall() |
||
420 | if rows_meters is not None and len(rows_meters) > 0: |
||
421 | cursor.close() |
||
422 | cnx.disconnect() |
||
423 | raise falcon.HTTPError(falcon.HTTP_400, |
||
424 | title='API.BAD_REQUEST', |
||
425 | description='API.THERE_IS_RELATION_WITH_METERS') |
||
426 | |||
427 | # check relation with offline meter |
||
428 | cursor.execute(" SELECT offline_meter_id " |
||
429 | " FROM tbl_tenants_offline_meters " |
||
430 | " WHERE tenant_id = %s ", |
||
431 | (id_,)) |
||
432 | rows_offline_meters = cursor.fetchall() |
||
433 | if rows_offline_meters is not None and len(rows_offline_meters) > 0: |
||
434 | cursor.close() |
||
435 | cnx.disconnect() |
||
436 | raise falcon.HTTPError(falcon.HTTP_400, |
||
437 | title='API.BAD_REQUEST', |
||
438 | description='API.THERE_IS_RELATION_WITH_OFFLINE_METERS') |
||
439 | |||
440 | # check relation with points |
||
441 | cursor.execute(" SELECT point_id " |
||
442 | " FROM tbl_tenants_points " |
||
443 | " WHERE tenant_id = %s ", (id_,)) |
||
444 | rows_points = cursor.fetchall() |
||
445 | if rows_points is not None and len(rows_points) > 0: |
||
446 | cursor.close() |
||
447 | cnx.disconnect() |
||
448 | raise falcon.HTTPError(falcon.HTTP_400, |
||
449 | title='API.BAD_REQUEST', |
||
450 | description='API.THERE_IS_RELATION_WITH_POINTS') |
||
451 | |||
452 | # check relation with sensor |
||
453 | cursor.execute(" SELECT sensor_id " |
||
454 | " FROM tbl_tenants_sensors " |
||
455 | " WHERE tenant_id = %s ", |
||
456 | (id_,)) |
||
457 | rows_sensors = cursor.fetchall() |
||
458 | if rows_sensors is not None and len(rows_sensors) > 0: |
||
459 | cursor.close() |
||
460 | cnx.disconnect() |
||
461 | raise falcon.HTTPError(falcon.HTTP_400, |
||
462 | title='API.BAD_REQUEST', |
||
463 | description='API.THERE_IS_RELATION_WITH_SENSOR') |
||
464 | |||
465 | # check relation with virtual meter |
||
466 | cursor.execute(" SELECT virtual_meter_id " |
||
467 | " FROM tbl_tenants_virtual_meters " |
||
468 | " WHERE tenant_id = %s ", |
||
469 | (id_,)) |
||
470 | rows_virtual_meters = cursor.fetchall() |
||
471 | if rows_virtual_meters is not None and len(rows_virtual_meters) > 0: |
||
472 | cursor.close() |
||
473 | cnx.disconnect() |
||
474 | raise falcon.HTTPError(falcon.HTTP_400, |
||
475 | title='API.BAD_REQUEST', |
||
476 | description='API.THERE_IS_RELATION_WITH_VIRTUAL_METER') |
||
477 | |||
478 | cursor.execute(" DELETE FROM tbl_tenants WHERE id = %s ", (id_,)) |
||
479 | cnx.commit() |
||
480 | |||
481 | cursor.close() |
||
482 | cnx.disconnect() |
||
483 | |||
484 | resp.status = falcon.HTTP_204 |
||
485 | |||
486 | @staticmethod |
||
487 | def on_put(req, resp, id_): |
||
488 | """Handles PUT requests""" |
||
489 | try: |
||
490 | raw_json = req.stream.read().decode('utf-8') |
||
491 | except Exception as ex: |
||
492 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
493 | |||
494 | if not id_.isdigit() or int(id_) <= 0: |
||
495 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
496 | description='API.INVALID_TENANT_ID') |
||
497 | |||
498 | new_values = json.loads(raw_json) |
||
499 | |||
500 | if 'name' not in new_values['data'].keys() or \ |
||
501 | not isinstance(new_values['data']['name'], str) or \ |
||
502 | len(str.strip(new_values['data']['name'])) == 0: |
||
503 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
504 | description='API.INVALID_TENANT_NAME') |
||
505 | name = str.strip(new_values['data']['name']) |
||
506 | |||
507 | if 'buildings' not in new_values['data'].keys() or \ |
||
508 | not isinstance(new_values['data']['buildings'], str) or \ |
||
509 | len(str.strip(new_values['data']['buildings'])) == 0: |
||
510 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
511 | description='API.INVALID_BUILDINGS_VALUE') |
||
512 | buildings = str.strip(new_values['data']['buildings']) |
||
513 | |||
514 | if 'floors' not in new_values['data'].keys() or \ |
||
515 | not isinstance(new_values['data']['floors'], str) or \ |
||
516 | len(str.strip(new_values['data']['floors'])) == 0: |
||
517 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
518 | description='API.INVALID_FLOORS_VALUE') |
||
519 | floors = str.strip(new_values['data']['floors']) |
||
520 | |||
521 | if 'rooms' not in new_values['data'].keys() or \ |
||
522 | not isinstance(new_values['data']['rooms'], str) or \ |
||
523 | len(str.strip(new_values['data']['rooms'])) == 0: |
||
524 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
525 | description='API.INVALID_ROOMS_VALUE') |
||
526 | rooms = str.strip(new_values['data']['rooms']) |
||
527 | |||
528 | if 'area' not in new_values['data'].keys() or \ |
||
529 | not (isinstance(new_values['data']['area'], float) or |
||
530 | isinstance(new_values['data']['area'], int)): |
||
531 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
532 | description='API.INVALID_AREA_VALUE') |
||
533 | area = new_values['data']['area'] |
||
534 | |||
535 | if 'tenant_type_id' not in new_values['data'].keys() or \ |
||
536 | not isinstance(new_values['data']['tenant_type_id'], int) or \ |
||
537 | new_values['data']['tenant_type_id'] <= 0: |
||
538 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
539 | description='API.INVALID_TENANT_TYPE_ID') |
||
540 | tenant_type_id = new_values['data']['tenant_type_id'] |
||
541 | |||
542 | if 'is_input_counted' not in new_values['data'].keys() or \ |
||
543 | not isinstance(new_values['data']['is_input_counted'], bool): |
||
544 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
545 | description='API.INVALID_IS_INPUT_COUNTED_VALUE') |
||
546 | is_input_counted = new_values['data']['is_input_counted'] |
||
547 | |||
548 | if 'is_key_tenant' not in new_values['data'].keys() or \ |
||
549 | not isinstance(new_values['data']['is_key_tenant'], bool): |
||
550 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
551 | description='API.INVALID_IS_KEY_TENANT_VALUE') |
||
552 | is_key_tenant = new_values['data']['is_key_tenant'] |
||
553 | |||
554 | if 'lease_number' not in new_values['data'].keys() or \ |
||
555 | not isinstance(new_values['data']['lease_number'], str) or \ |
||
556 | len(str.strip(new_values['data']['lease_number'])) == 0: |
||
557 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
558 | description='API.INVALID_LEASE_NUMBER_VALUE') |
||
559 | lease_number = str.strip(new_values['data']['lease_number']) |
||
560 | |||
561 | if 'is_in_lease' not in new_values['data'].keys() or \ |
||
562 | not isinstance(new_values['data']['is_in_lease'], bool): |
||
563 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
564 | description='API.INVALID_IS_IN_LEASE_VALUE') |
||
565 | is_in_lease = new_values['data']['is_in_lease'] |
||
566 | |||
567 | timezone_offset = int(config.utc_offset[1:3]) * 60 + int(config.utc_offset[4:6]) |
||
568 | if config.utc_offset[0] == '-': |
||
569 | timezone_offset = -timezone_offset |
||
570 | |||
571 | # todo: validate datetime values |
||
572 | lease_start_datetime_utc = datetime.strptime(new_values['data']['lease_start_datetime_utc'], |
||
573 | '%Y-%m-%dT%H:%M:%S') |
||
574 | lease_start_datetime_utc = lease_start_datetime_utc.replace(tzinfo=timezone.utc) |
||
575 | lease_start_datetime_utc -= timedelta(minutes=timezone_offset) |
||
576 | |||
577 | lease_end_datetime_utc = datetime.strptime(new_values['data']['lease_end_datetime_utc'], |
||
578 | '%Y-%m-%dT%H:%M:%S') |
||
579 | lease_end_datetime_utc = lease_end_datetime_utc.replace(tzinfo=timezone.utc) |
||
580 | lease_end_datetime_utc -= timedelta(minutes=timezone_offset) |
||
581 | |||
582 | if 'contact_id' not in new_values['data'].keys() or \ |
||
583 | not isinstance(new_values['data']['contact_id'], int) or \ |
||
584 | new_values['data']['contact_id'] <= 0: |
||
585 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
586 | description='API.INVALID_CONTACT_ID') |
||
587 | contact_id = new_values['data']['contact_id'] |
||
588 | |||
589 | if 'cost_center_id' not in new_values['data'].keys() or \ |
||
590 | not isinstance(new_values['data']['cost_center_id'], int) or \ |
||
591 | new_values['data']['cost_center_id'] <= 0: |
||
592 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
593 | description='API.INVALID_COST_CENTER_ID') |
||
594 | cost_center_id = new_values['data']['cost_center_id'] |
||
595 | |||
596 | if 'description' in new_values['data'].keys() and \ |
||
597 | new_values['data']['description'] is not None and \ |
||
598 | len(str(new_values['data']['description'])) > 0: |
||
599 | description = str.strip(new_values['data']['description']) |
||
600 | else: |
||
601 | description = None |
||
602 | |||
603 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
604 | cursor = cnx.cursor() |
||
605 | |||
606 | cursor.execute(" SELECT name " |
||
607 | " FROM tbl_tenants " |
||
608 | " WHERE id = %s ", (id_,)) |
||
609 | if cursor.fetchone() is None: |
||
610 | cursor.close() |
||
611 | cnx.disconnect() |
||
612 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
613 | description='API.TENANT_NOT_FOUND') |
||
614 | |||
615 | cursor.execute(" SELECT name " |
||
616 | " FROM tbl_tenants " |
||
617 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
618 | if cursor.fetchone() is not None: |
||
619 | cursor.close() |
||
620 | cnx.disconnect() |
||
621 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
622 | description='API.TENANT_NAME_IS_ALREADY_IN_USE') |
||
623 | |||
624 | cursor.execute(" SELECT name " |
||
625 | " FROM tbl_tenant_types " |
||
626 | " WHERE id = %s ", |
||
627 | (tenant_type_id,)) |
||
628 | if cursor.fetchone() is None: |
||
629 | cursor.close() |
||
630 | cnx.disconnect() |
||
631 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
632 | description='API.TENANT_TYPE_NOT_FOUND') |
||
633 | |||
634 | cursor.execute(" SELECT name " |
||
635 | " FROM tbl_contacts " |
||
636 | " WHERE id = %s ", |
||
637 | (new_values['data']['contact_id'],)) |
||
638 | row = cursor.fetchone() |
||
639 | if row is None: |
||
640 | cursor.close() |
||
641 | cnx.disconnect() |
||
642 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
643 | description='API.CONTACT_NOT_FOUND') |
||
644 | |||
645 | cursor.execute(" SELECT name " |
||
646 | " FROM tbl_cost_centers " |
||
647 | " WHERE id = %s ", |
||
648 | (new_values['data']['cost_center_id'],)) |
||
649 | row = cursor.fetchone() |
||
650 | if row is None: |
||
651 | cursor.close() |
||
652 | cnx.disconnect() |
||
653 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
654 | description='API.COST_CENTER_NOT_FOUND') |
||
655 | |||
656 | update_row = (" UPDATE tbl_tenants " |
||
657 | " SET name = %s, buildings = %s, floors = %s, rooms = %s, area = %s, " |
||
658 | " tenant_type_id = %s, is_input_counted = %s, " |
||
659 | " is_key_tenant = %s, lease_number = %s, lease_start_datetime_utc = %s, " |
||
660 | " lease_end_datetime_utc = %s, is_in_lease = %s, contact_id = %s, cost_center_id = %s, " |
||
661 | " description = %s " |
||
662 | " WHERE id = %s ") |
||
663 | cursor.execute(update_row, (name, |
||
664 | buildings, |
||
665 | floors, |
||
666 | rooms, |
||
667 | area, |
||
668 | tenant_type_id, |
||
669 | is_input_counted, |
||
670 | is_key_tenant, |
||
671 | lease_number, |
||
672 | lease_start_datetime_utc, |
||
673 | lease_end_datetime_utc, |
||
674 | is_in_lease, |
||
675 | contact_id, |
||
676 | cost_center_id, |
||
677 | description, |
||
678 | id_)) |
||
679 | cnx.commit() |
||
680 | |||
681 | cursor.close() |
||
682 | cnx.disconnect() |
||
683 | |||
684 | resp.status = falcon.HTTP_200 |
||
685 | |||
686 | |||
687 | View Code Duplication | class TenantMeterCollection: |
|
688 | @staticmethod |
||
689 | def __init__(): |
||
690 | pass |
||
691 | |||
692 | @staticmethod |
||
693 | def on_options(req, resp, id_): |
||
694 | resp.status = falcon.HTTP_200 |
||
695 | |||
696 | @staticmethod |
||
697 | def on_get(req, resp, id_): |
||
698 | if not id_.isdigit() or int(id_) <= 0: |
||
699 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
700 | description='API.INVALID_TENANT_ID') |
||
701 | |||
702 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
703 | cursor = cnx.cursor(dictionary=True) |
||
704 | |||
705 | cursor.execute(" SELECT name " |
||
706 | " FROM tbl_tenants " |
||
707 | " WHERE id = %s ", (id_,)) |
||
708 | if cursor.fetchone() is None: |
||
709 | cursor.close() |
||
710 | cnx.disconnect() |
||
711 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
712 | description='API.TENANT_NOT_FOUND') |
||
713 | |||
714 | query = (" SELECT id, name, uuid " |
||
715 | " FROM tbl_energy_categories ") |
||
716 | cursor.execute(query) |
||
717 | rows_energy_categories = cursor.fetchall() |
||
718 | |||
719 | energy_category_dict = dict() |
||
720 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
||
721 | for row in rows_energy_categories: |
||
722 | energy_category_dict[row['id']] = {"id": row['id'], |
||
723 | "name": row['name'], |
||
724 | "uuid": row['uuid']} |
||
725 | |||
726 | query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id " |
||
727 | " FROM tbl_tenants t, tbl_tenants_meters tm, tbl_meters m " |
||
728 | " WHERE tm.tenant_id = t.id AND m.id = tm.meter_id AND t.id = %s " |
||
729 | " ORDER BY m.id ") |
||
730 | cursor.execute(query, (id_,)) |
||
731 | rows = cursor.fetchall() |
||
732 | |||
733 | result = list() |
||
734 | if rows is not None and len(rows) > 0: |
||
735 | for row in rows: |
||
736 | energy_category = energy_category_dict.get(row['energy_category_id'], None) |
||
737 | meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'], |
||
738 | "energy_category": energy_category} |
||
739 | result.append(meta_result) |
||
740 | |||
741 | resp.body = json.dumps(result) |
||
742 | |||
743 | @staticmethod |
||
744 | def on_post(req, resp, id_): |
||
745 | """Handles POST requests""" |
||
746 | try: |
||
747 | raw_json = req.stream.read().decode('utf-8') |
||
748 | except Exception as ex: |
||
749 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
750 | |||
751 | if not id_.isdigit() or int(id_) <= 0: |
||
752 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
753 | description='API.INVALID_TENANT_ID') |
||
754 | |||
755 | new_values = json.loads(raw_json) |
||
756 | |||
757 | if 'meter_id' not in new_values['data'].keys() or \ |
||
758 | not isinstance(new_values['data']['meter_id'], int) or \ |
||
759 | new_values['data']['meter_id'] <= 0: |
||
760 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
761 | description='API.INVALID_METER_ID') |
||
762 | meter_id = new_values['data']['meter_id'] |
||
763 | |||
764 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
765 | cursor = cnx.cursor() |
||
766 | |||
767 | cursor.execute(" SELECT name " |
||
768 | " from tbl_tenants " |
||
769 | " WHERE id = %s ", (id_,)) |
||
770 | if cursor.fetchone() is None: |
||
771 | cursor.close() |
||
772 | cnx.disconnect() |
||
773 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
774 | description='API.TENANT_NOT_FOUND') |
||
775 | |||
776 | cursor.execute(" SELECT name " |
||
777 | " FROM tbl_meters " |
||
778 | " WHERE id = %s ", (meter_id,)) |
||
779 | if cursor.fetchone() is None: |
||
780 | cursor.close() |
||
781 | cnx.disconnect() |
||
782 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
783 | description='API.METER_NOT_FOUND') |
||
784 | |||
785 | query = (" SELECT id " |
||
786 | " FROM tbl_tenants_meters " |
||
787 | " WHERE tenant_id = %s AND meter_id = %s") |
||
788 | cursor.execute(query, (id_, meter_id,)) |
||
789 | if cursor.fetchone() is not None: |
||
790 | cursor.close() |
||
791 | cnx.disconnect() |
||
792 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', |
||
793 | description='API.TENANT_METER_RELATION_EXISTED') |
||
794 | |||
795 | add_row = (" INSERT INTO tbl_tenants_meters (tenant_id, meter_id) " |
||
796 | " VALUES (%s, %s) ") |
||
797 | cursor.execute(add_row, (id_, meter_id,)) |
||
798 | new_id = cursor.lastrowid |
||
799 | cnx.commit() |
||
800 | cursor.close() |
||
801 | cnx.disconnect() |
||
802 | |||
803 | resp.status = falcon.HTTP_201 |
||
804 | resp.location = '/tenants/' + str(id_) + '/meters/' + str(meter_id) |
||
805 | |||
806 | |||
807 | View Code Duplication | class TenantMeterItem: |
|
808 | @staticmethod |
||
809 | def __init__(): |
||
810 | pass |
||
811 | |||
812 | @staticmethod |
||
813 | def on_options(req, resp, id_, mid): |
||
814 | resp.status = falcon.HTTP_200 |
||
815 | |||
816 | @staticmethod |
||
817 | def on_delete(req, resp, id_, mid): |
||
818 | if not id_.isdigit() or int(id_) <= 0: |
||
819 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
820 | description='API.INVALID_TENANT_ID') |
||
821 | |||
822 | if not mid.isdigit() or int(mid) <= 0: |
||
823 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
824 | description='API.INVALID_METER_ID') |
||
825 | |||
826 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
827 | cursor = cnx.cursor() |
||
828 | |||
829 | cursor.execute(" SELECT name " |
||
830 | " FROM tbl_tenants " |
||
831 | " WHERE id = %s ", (id_,)) |
||
832 | if cursor.fetchone() is None: |
||
833 | cursor.close() |
||
834 | cnx.disconnect() |
||
835 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
836 | description='API.TENANT_NOT_FOUND') |
||
837 | |||
838 | cursor.execute(" SELECT name " |
||
839 | " FROM tbl_meters " |
||
840 | " WHERE id = %s ", (mid,)) |
||
841 | if cursor.fetchone() is None: |
||
842 | cursor.close() |
||
843 | cnx.disconnect() |
||
844 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
845 | description='API.METER_NOT_FOUND') |
||
846 | |||
847 | cursor.execute(" SELECT id " |
||
848 | " FROM tbl_tenants_meters " |
||
849 | " WHERE tenant_id = %s AND meter_id = %s ", (id_, mid)) |
||
850 | if cursor.fetchone() is None: |
||
851 | cursor.close() |
||
852 | cnx.disconnect() |
||
853 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
854 | description='API.TENANT_METER_RELATION_NOT_FOUND') |
||
855 | |||
856 | cursor.execute(" DELETE FROM tbl_tenants_meters WHERE tenant_id = %s AND meter_id = %s ", (id_, mid)) |
||
857 | cnx.commit() |
||
858 | |||
859 | cursor.close() |
||
860 | cnx.disconnect() |
||
861 | |||
862 | resp.status = falcon.HTTP_204 |
||
863 | |||
864 | |||
865 | View Code Duplication | class TenantOfflineMeterCollection: |
|
866 | @staticmethod |
||
867 | def __init__(): |
||
868 | pass |
||
869 | |||
870 | @staticmethod |
||
871 | def on_options(req, resp, id_): |
||
872 | resp.status = falcon.HTTP_200 |
||
873 | |||
874 | @staticmethod |
||
875 | def on_get(req, resp, id_): |
||
876 | if not id_.isdigit() or int(id_) <= 0: |
||
877 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
878 | description='API.INVALID_TENANT_ID') |
||
879 | |||
880 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
881 | cursor = cnx.cursor(dictionary=True) |
||
882 | |||
883 | cursor.execute(" SELECT name " |
||
884 | " FROM tbl_tenants " |
||
885 | " WHERE id = %s ", (id_,)) |
||
886 | if cursor.fetchone() is None: |
||
887 | cursor.close() |
||
888 | cnx.disconnect() |
||
889 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
890 | description='API.TENANT_NOT_FOUND') |
||
891 | |||
892 | query = (" SELECT id, name, uuid " |
||
893 | " FROM tbl_energy_categories ") |
||
894 | cursor.execute(query) |
||
895 | rows_energy_categories = cursor.fetchall() |
||
896 | |||
897 | energy_category_dict = dict() |
||
898 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
||
899 | for row in rows_energy_categories: |
||
900 | energy_category_dict[row['id']] = {"id": row['id'], |
||
901 | "name": row['name'], |
||
902 | "uuid": row['uuid']} |
||
903 | |||
904 | query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id " |
||
905 | " FROM tbl_tenants s, tbl_tenants_offline_meters sm, tbl_offline_meters m " |
||
906 | " WHERE sm.tenant_id = s.id AND m.id = sm.offline_meter_id AND s.id = %s " |
||
907 | " ORDER BY m.id ") |
||
908 | cursor.execute(query, (id_,)) |
||
909 | rows = cursor.fetchall() |
||
910 | |||
911 | result = list() |
||
912 | if rows is not None and len(rows) > 0: |
||
913 | for row in rows: |
||
914 | energy_category = energy_category_dict.get(row['energy_category_id'], None) |
||
915 | meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'], |
||
916 | "energy_category": energy_category} |
||
917 | result.append(meta_result) |
||
918 | |||
919 | resp.body = json.dumps(result) |
||
920 | |||
921 | @staticmethod |
||
922 | def on_post(req, resp, id_): |
||
923 | """Handles POST requests""" |
||
924 | try: |
||
925 | raw_json = req.stream.read().decode('utf-8') |
||
926 | except Exception as ex: |
||
927 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
928 | |||
929 | if not id_.isdigit() or int(id_) <= 0: |
||
930 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
931 | description='API.INVALID_TENANT_ID') |
||
932 | |||
933 | new_values = json.loads(raw_json) |
||
934 | |||
935 | if 'offline_meter_id' not in new_values['data'].keys() or \ |
||
936 | not isinstance(new_values['data']['offline_meter_id'], int) or \ |
||
937 | new_values['data']['offline_meter_id'] <= 0: |
||
938 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
939 | description='API.INVALID_OFFLINE_METER_ID') |
||
940 | offline_meter_id = new_values['data']['offline_meter_id'] |
||
941 | |||
942 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
943 | cursor = cnx.cursor() |
||
944 | |||
945 | cursor.execute(" SELECT name " |
||
946 | " from tbl_tenants " |
||
947 | " WHERE id = %s ", (id_,)) |
||
948 | if cursor.fetchone() is None: |
||
949 | cursor.close() |
||
950 | cnx.disconnect() |
||
951 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
952 | description='API.TENANT_NOT_FOUND') |
||
953 | |||
954 | cursor.execute(" SELECT name " |
||
955 | " FROM tbl_offline_meters " |
||
956 | " WHERE id = %s ", (offline_meter_id,)) |
||
957 | if cursor.fetchone() is None: |
||
958 | cursor.close() |
||
959 | cnx.disconnect() |
||
960 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
961 | description='API.OFFLINE_METER_NOT_FOUND') |
||
962 | |||
963 | query = (" SELECT id " |
||
964 | " FROM tbl_tenants_offline_meters " |
||
965 | " WHERE tenant_id = %s AND offline_meter_id = %s") |
||
966 | cursor.execute(query, (id_, offline_meter_id,)) |
||
967 | if cursor.fetchone() is not None: |
||
968 | cursor.close() |
||
969 | cnx.disconnect() |
||
970 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', |
||
971 | description='API.TENANT_OFFLINE_METER_RELATION_EXISTED') |
||
972 | |||
973 | add_row = (" INSERT INTO tbl_tenants_offline_meters (tenant_id, offline_meter_id) " |
||
974 | " VALUES (%s, %s) ") |
||
975 | cursor.execute(add_row, (id_, offline_meter_id,)) |
||
976 | new_id = cursor.lastrowid |
||
977 | cnx.commit() |
||
978 | cursor.close() |
||
979 | cnx.disconnect() |
||
980 | |||
981 | resp.status = falcon.HTTP_201 |
||
982 | resp.location = '/tenants/' + str(id_) + '/offlinemeters/' + str(offline_meter_id) |
||
983 | |||
984 | |||
985 | View Code Duplication | class TenantOfflineMeterItem: |
|
986 | @staticmethod |
||
987 | def __init__(): |
||
988 | pass |
||
989 | |||
990 | @staticmethod |
||
991 | def on_options(req, resp, id_, mid): |
||
992 | resp.status = falcon.HTTP_200 |
||
993 | |||
994 | @staticmethod |
||
995 | def on_delete(req, resp, id_, mid): |
||
996 | if not id_.isdigit() or int(id_) <= 0: |
||
997 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
998 | description='API.INVALID_TENANT_ID') |
||
999 | |||
1000 | if not mid.isdigit() or int(mid) <= 0: |
||
1001 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1002 | description='API.INVALID_OFFLINE_METER_ID') |
||
1003 | |||
1004 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1005 | cursor = cnx.cursor() |
||
1006 | |||
1007 | cursor.execute(" SELECT name " |
||
1008 | " FROM tbl_tenants " |
||
1009 | " WHERE id = %s ", (id_,)) |
||
1010 | if cursor.fetchone() is None: |
||
1011 | cursor.close() |
||
1012 | cnx.disconnect() |
||
1013 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1014 | description='API.TENANT_NOT_FOUND') |
||
1015 | |||
1016 | cursor.execute(" SELECT name " |
||
1017 | " FROM tbl_offline_meters " |
||
1018 | " WHERE id = %s ", (mid,)) |
||
1019 | if cursor.fetchone() is None: |
||
1020 | cursor.close() |
||
1021 | cnx.disconnect() |
||
1022 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1023 | description='API.OFFLINE_METER_NOT_FOUND') |
||
1024 | |||
1025 | cursor.execute(" SELECT id " |
||
1026 | " FROM tbl_tenants_offline_meters " |
||
1027 | " WHERE tenant_id = %s AND offline_meter_id = %s ", (id_, mid)) |
||
1028 | if cursor.fetchone() is None: |
||
1029 | cursor.close() |
||
1030 | cnx.disconnect() |
||
1031 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1032 | description='API.TENANT_OFFLINE_METER_RELATION_NOT_FOUND') |
||
1033 | |||
1034 | cursor.execute(" DELETE FROM tbl_tenants_offline_meters " |
||
1035 | " WHERE tenant_id = %s AND offline_meter_id = %s ", (id_, mid)) |
||
1036 | cnx.commit() |
||
1037 | |||
1038 | cursor.close() |
||
1039 | cnx.disconnect() |
||
1040 | |||
1041 | resp.status = falcon.HTTP_204 |
||
1042 | |||
1043 | |||
1044 | View Code Duplication | class TenantPointCollection: |
|
1045 | @staticmethod |
||
1046 | def __init__(): |
||
1047 | pass |
||
1048 | |||
1049 | @staticmethod |
||
1050 | def on_options(req, resp, id_): |
||
1051 | resp.status = falcon.HTTP_200 |
||
1052 | |||
1053 | @staticmethod |
||
1054 | def on_get(req, resp, id_): |
||
1055 | if not id_.isdigit() or int(id_) <= 0: |
||
1056 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1057 | description='API.INVALID_TENANT_ID') |
||
1058 | |||
1059 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1060 | cursor = cnx.cursor(dictionary=True) |
||
1061 | |||
1062 | cursor.execute(" SELECT name " |
||
1063 | " FROM tbl_tenants " |
||
1064 | " WHERE id = %s ", (id_,)) |
||
1065 | if cursor.fetchone() is None: |
||
1066 | cursor.close() |
||
1067 | cnx.disconnect() |
||
1068 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1069 | description='API.TENANT_NOT_FOUND') |
||
1070 | |||
1071 | query = (" SELECT id, name, uuid " |
||
1072 | " FROM tbl_data_sources ") |
||
1073 | cursor.execute(query) |
||
1074 | rows_data_sources = cursor.fetchall() |
||
1075 | |||
1076 | data_source_dict = dict() |
||
1077 | if rows_data_sources is not None and len(rows_data_sources) > 0: |
||
1078 | for row in rows_data_sources: |
||
1079 | data_source_dict[row['id']] = {"id": row['id'], |
||
1080 | "name": row['name'], |
||
1081 | "uuid": row['uuid']} |
||
1082 | |||
1083 | query = (" SELECT p.id, p.name, p.data_source_id " |
||
1084 | " FROM tbl_tenants t, tbl_tenants_points tp, tbl_points p " |
||
1085 | " WHERE tp.tenant_id = t.id AND p.id = tp.point_id AND t.id = %s " |
||
1086 | " ORDER BY p.id ") |
||
1087 | cursor.execute(query, (id_,)) |
||
1088 | rows = cursor.fetchall() |
||
1089 | |||
1090 | result = list() |
||
1091 | if rows is not None and len(rows) > 0: |
||
1092 | for row in rows: |
||
1093 | data_source = data_source_dict.get(row['data_source_id'], None) |
||
1094 | meta_result = {"id": row['id'], "name": row['name'], "data_source": data_source} |
||
1095 | result.append(meta_result) |
||
1096 | |||
1097 | resp.body = json.dumps(result) |
||
1098 | |||
1099 | @staticmethod |
||
1100 | def on_post(req, resp, id_): |
||
1101 | """Handles POST requests""" |
||
1102 | try: |
||
1103 | raw_json = req.stream.read().decode('utf-8') |
||
1104 | except Exception as ex: |
||
1105 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
1106 | |||
1107 | if not id_.isdigit() or int(id_) <= 0: |
||
1108 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1109 | description='API.INVALID_TENANT_ID') |
||
1110 | |||
1111 | new_values = json.loads(raw_json) |
||
1112 | |||
1113 | if 'point_id' not in new_values['data'].keys() or \ |
||
1114 | not isinstance(new_values['data']['point_id'], int) or \ |
||
1115 | new_values['data']['point_id'] <= 0: |
||
1116 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1117 | description='API.INVALID_POINT_ID') |
||
1118 | point_id = new_values['data']['point_id'] |
||
1119 | |||
1120 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1121 | cursor = cnx.cursor() |
||
1122 | |||
1123 | cursor.execute(" SELECT name " |
||
1124 | " from tbl_tenants " |
||
1125 | " WHERE id = %s ", (id_,)) |
||
1126 | if cursor.fetchone() is None: |
||
1127 | cursor.close() |
||
1128 | cnx.disconnect() |
||
1129 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1130 | description='API.TENANT_NOT_FOUND') |
||
1131 | |||
1132 | cursor.execute(" SELECT name " |
||
1133 | " FROM tbl_points " |
||
1134 | " WHERE id = %s ", (point_id,)) |
||
1135 | if cursor.fetchone() is None: |
||
1136 | cursor.close() |
||
1137 | cnx.disconnect() |
||
1138 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1139 | description='API.POINT_NOT_FOUND') |
||
1140 | |||
1141 | query = (" SELECT id " |
||
1142 | " FROM tbl_tenants_points " |
||
1143 | " WHERE tenant_id = %s AND point_id = %s") |
||
1144 | cursor.execute(query, (id_, point_id,)) |
||
1145 | if cursor.fetchone() is not None: |
||
1146 | cursor.close() |
||
1147 | cnx.disconnect() |
||
1148 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', |
||
1149 | description='API.TENANT_POINT_RELATION_EXISTED') |
||
1150 | |||
1151 | add_row = (" INSERT INTO tbl_tenants_points (tenant_id, point_id) " |
||
1152 | " VALUES (%s, %s) ") |
||
1153 | cursor.execute(add_row, (id_, point_id,)) |
||
1154 | new_id = cursor.lastrowid |
||
1155 | cnx.commit() |
||
1156 | cursor.close() |
||
1157 | cnx.disconnect() |
||
1158 | |||
1159 | resp.status = falcon.HTTP_201 |
||
1160 | resp.location = '/tenants/' + str(id_) + '/points/' + str(point_id) |
||
1161 | |||
1162 | |||
1163 | View Code Duplication | class TenantPointItem: |
|
1164 | @staticmethod |
||
1165 | def __init__(): |
||
1166 | pass |
||
1167 | |||
1168 | @staticmethod |
||
1169 | def on_options(req, resp, id_, pid): |
||
1170 | resp.status = falcon.HTTP_200 |
||
1171 | |||
1172 | @staticmethod |
||
1173 | def on_delete(req, resp, id_, pid): |
||
1174 | if not id_.isdigit() or int(id_) <= 0: |
||
1175 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1176 | description='API.INVALID_TENANT_ID') |
||
1177 | |||
1178 | if not pid.isdigit() or int(pid) <= 0: |
||
1179 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1180 | description='API.INVALID_POINT_ID') |
||
1181 | |||
1182 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1183 | cursor = cnx.cursor() |
||
1184 | |||
1185 | cursor.execute(" SELECT name " |
||
1186 | " FROM tbl_tenants " |
||
1187 | " WHERE id = %s ", (id_,)) |
||
1188 | if cursor.fetchone() is None: |
||
1189 | cursor.close() |
||
1190 | cnx.disconnect() |
||
1191 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1192 | description='API.TENANT_NOT_FOUND') |
||
1193 | |||
1194 | cursor.execute(" SELECT name " |
||
1195 | " FROM tbl_points " |
||
1196 | " WHERE id = %s ", (pid,)) |
||
1197 | if cursor.fetchone() is None: |
||
1198 | cursor.close() |
||
1199 | cnx.disconnect() |
||
1200 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1201 | description='API.POINT_NOT_FOUND') |
||
1202 | |||
1203 | cursor.execute(" SELECT id " |
||
1204 | " FROM tbl_tenants_points " |
||
1205 | " WHERE tenant_id = %s AND point_id = %s ", (id_, pid)) |
||
1206 | if cursor.fetchone() is None: |
||
1207 | cursor.close() |
||
1208 | cnx.disconnect() |
||
1209 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1210 | description='API.TENANT_POINT_RELATION_NOT_FOUND') |
||
1211 | |||
1212 | cursor.execute(" DELETE FROM tbl_tenants_points " |
||
1213 | " WHERE tenant_id = %s AND point_id = %s ", (id_, pid)) |
||
1214 | cnx.commit() |
||
1215 | |||
1216 | cursor.close() |
||
1217 | cnx.disconnect() |
||
1218 | |||
1219 | resp.status = falcon.HTTP_204 |
||
1220 | |||
1221 | |||
1222 | View Code Duplication | class TenantSensorCollection: |
|
1223 | @staticmethod |
||
1224 | def __init__(): |
||
1225 | pass |
||
1226 | |||
1227 | @staticmethod |
||
1228 | def on_options(req, resp, id_): |
||
1229 | resp.status = falcon.HTTP_200 |
||
1230 | |||
1231 | @staticmethod |
||
1232 | def on_get(req, resp, id_): |
||
1233 | if not id_.isdigit() or int(id_) <= 0: |
||
1234 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1235 | description='API.INVALID_TENANT_ID') |
||
1236 | |||
1237 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1238 | cursor = cnx.cursor() |
||
1239 | |||
1240 | cursor.execute(" SELECT name " |
||
1241 | " FROM tbl_tenants " |
||
1242 | " WHERE id = %s ", (id_,)) |
||
1243 | if cursor.fetchone() is None: |
||
1244 | cursor.close() |
||
1245 | cnx.disconnect() |
||
1246 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1247 | description='API.TENANT_NOT_FOUND') |
||
1248 | |||
1249 | query = (" SELECT s.id, s.name, s.uuid " |
||
1250 | " FROM tbl_tenants t, tbl_tenants_sensors ts, tbl_sensors s " |
||
1251 | " WHERE ts.tenant_id = t.id AND s.id = ts.sensor_id AND t.id = %s " |
||
1252 | " ORDER BY s.id ") |
||
1253 | cursor.execute(query, (id_,)) |
||
1254 | rows = cursor.fetchall() |
||
1255 | |||
1256 | result = list() |
||
1257 | if rows is not None and len(rows) > 0: |
||
1258 | for row in rows: |
||
1259 | meta_result = {"id": row[0], "name": row[1], "uuid": row[2]} |
||
1260 | result.append(meta_result) |
||
1261 | |||
1262 | resp.body = json.dumps(result) |
||
1263 | |||
1264 | @staticmethod |
||
1265 | def on_post(req, resp, id_): |
||
1266 | """Handles POST requests""" |
||
1267 | try: |
||
1268 | raw_json = req.stream.read().decode('utf-8') |
||
1269 | except Exception as ex: |
||
1270 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
1271 | |||
1272 | if not id_.isdigit() or int(id_) <= 0: |
||
1273 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1274 | description='API.INVALID_TENANT_ID') |
||
1275 | |||
1276 | new_values = json.loads(raw_json) |
||
1277 | |||
1278 | if 'sensor_id' not in new_values['data'].keys() or \ |
||
1279 | not isinstance(new_values['data']['sensor_id'], int) or \ |
||
1280 | new_values['data']['sensor_id'] <= 0: |
||
1281 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1282 | description='API.INVALID_SENSOR_ID') |
||
1283 | sensor_id = new_values['data']['sensor_id'] |
||
1284 | |||
1285 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1286 | cursor = cnx.cursor() |
||
1287 | |||
1288 | cursor.execute(" SELECT name " |
||
1289 | " from tbl_tenants " |
||
1290 | " WHERE id = %s ", (id_,)) |
||
1291 | if cursor.fetchone() is None: |
||
1292 | cursor.close() |
||
1293 | cnx.disconnect() |
||
1294 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1295 | description='API.TENANT_NOT_FOUND') |
||
1296 | |||
1297 | cursor.execute(" SELECT name " |
||
1298 | " FROM tbl_sensors " |
||
1299 | " WHERE id = %s ", (sensor_id,)) |
||
1300 | if cursor.fetchone() is None: |
||
1301 | cursor.close() |
||
1302 | cnx.disconnect() |
||
1303 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1304 | description='API.SENSOR_NOT_FOUND') |
||
1305 | |||
1306 | query = (" SELECT id " |
||
1307 | " FROM tbl_tenants_sensors " |
||
1308 | " WHERE tenant_id = %s AND sensor_id = %s") |
||
1309 | cursor.execute(query, (id_, sensor_id,)) |
||
1310 | if cursor.fetchone() is not None: |
||
1311 | cursor.close() |
||
1312 | cnx.disconnect() |
||
1313 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', |
||
1314 | description='API.TENANT_SENSOR_RELATION_EXISTED') |
||
1315 | |||
1316 | add_row = (" INSERT INTO tbl_tenants_sensors (tenant_id, sensor_id) " |
||
1317 | " VALUES (%s, %s) ") |
||
1318 | cursor.execute(add_row, (id_, sensor_id,)) |
||
1319 | new_id = cursor.lastrowid |
||
1320 | cnx.commit() |
||
1321 | cursor.close() |
||
1322 | cnx.disconnect() |
||
1323 | |||
1324 | resp.status = falcon.HTTP_201 |
||
1325 | resp.location = '/tenants/' + str(id_) + '/sensors/' + str(sensor_id) |
||
1326 | |||
1327 | |||
1328 | View Code Duplication | class TenantSensorItem: |
|
1329 | @staticmethod |
||
1330 | def __init__(): |
||
1331 | pass |
||
1332 | |||
1333 | @staticmethod |
||
1334 | def on_options(req, resp, id_, sid): |
||
1335 | resp.status = falcon.HTTP_200 |
||
1336 | |||
1337 | @staticmethod |
||
1338 | def on_delete(req, resp, id_, sid): |
||
1339 | if not id_.isdigit() or int(id_) <= 0: |
||
1340 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1341 | description='API.INVALID_TENANT_ID') |
||
1342 | |||
1343 | if not sid.isdigit() or int(sid) <= 0: |
||
1344 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1345 | description='API.INVALID_SENSOR_ID') |
||
1346 | |||
1347 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1348 | cursor = cnx.cursor() |
||
1349 | |||
1350 | cursor.execute(" SELECT name " |
||
1351 | " FROM tbl_tenants " |
||
1352 | " WHERE id = %s ", (id_,)) |
||
1353 | if cursor.fetchone() is None: |
||
1354 | cursor.close() |
||
1355 | cnx.disconnect() |
||
1356 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1357 | description='API.TENANT_NOT_FOUND') |
||
1358 | |||
1359 | cursor.execute(" SELECT name " |
||
1360 | " FROM tbl_sensors " |
||
1361 | " WHERE id = %s ", (sid,)) |
||
1362 | if cursor.fetchone() is None: |
||
1363 | cursor.close() |
||
1364 | cnx.disconnect() |
||
1365 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1366 | description='API.SENSOR_NOT_FOUND') |
||
1367 | |||
1368 | cursor.execute(" SELECT id " |
||
1369 | " FROM tbl_tenants_sensors " |
||
1370 | " WHERE tenant_id = %s AND sensor_id = %s ", (id_, sid)) |
||
1371 | if cursor.fetchone() is None: |
||
1372 | cursor.close() |
||
1373 | cnx.disconnect() |
||
1374 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1375 | description='API.TENANT_SENSOR_RELATION_NOT_FOUND') |
||
1376 | |||
1377 | cursor.execute(" DELETE FROM tbl_tenants_sensors WHERE tenant_id = %s AND sensor_id = %s ", (id_, sid)) |
||
1378 | cnx.commit() |
||
1379 | |||
1380 | cursor.close() |
||
1381 | cnx.disconnect() |
||
1382 | |||
1383 | resp.status = falcon.HTTP_204 |
||
1384 | |||
1385 | |||
1386 | View Code Duplication | class TenantVirtualMeterCollection: |
|
1387 | @staticmethod |
||
1388 | def __init__(): |
||
1389 | pass |
||
1390 | |||
1391 | @staticmethod |
||
1392 | def on_options(req, resp, id_): |
||
1393 | resp.status = falcon.HTTP_200 |
||
1394 | |||
1395 | @staticmethod |
||
1396 | def on_get(req, resp, id_): |
||
1397 | if not id_.isdigit() or int(id_) <= 0: |
||
1398 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1399 | description='API.INVALID_TENANT_ID') |
||
1400 | |||
1401 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1402 | cursor = cnx.cursor(dictionary=True) |
||
1403 | |||
1404 | cursor.execute(" SELECT name " |
||
1405 | " FROM tbl_tenants " |
||
1406 | " WHERE id = %s ", (id_,)) |
||
1407 | if cursor.fetchone() is None: |
||
1408 | cursor.close() |
||
1409 | cnx.disconnect() |
||
1410 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1411 | description='API.TENANT_NOT_FOUND') |
||
1412 | |||
1413 | query = (" SELECT id, name, uuid " |
||
1414 | " FROM tbl_energy_categories ") |
||
1415 | cursor.execute(query) |
||
1416 | rows_energy_categories = cursor.fetchall() |
||
1417 | |||
1418 | energy_category_dict = dict() |
||
1419 | if rows_energy_categories is not None and len(rows_energy_categories) > 0: |
||
1420 | for row in rows_energy_categories: |
||
1421 | energy_category_dict[row['id']] = {"id": row['id'], |
||
1422 | "name": row['name'], |
||
1423 | "uuid": row['uuid']} |
||
1424 | |||
1425 | query = (" SELECT m.id, m.name, m.uuid, m.energy_category_id " |
||
1426 | " FROM tbl_tenants t, tbl_tenants_virtual_meters tm, tbl_virtual_meters m " |
||
1427 | " WHERE tm.tenant_id = t.id AND m.id = tm.virtual_meter_id AND t.id = %s " |
||
1428 | " ORDER BY m.id ") |
||
1429 | cursor.execute(query, (id_,)) |
||
1430 | rows = cursor.fetchall() |
||
1431 | |||
1432 | result = list() |
||
1433 | if rows is not None and len(rows) > 0: |
||
1434 | for row in rows: |
||
1435 | energy_category = energy_category_dict.get(row['energy_category_id'], None) |
||
1436 | meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'], |
||
1437 | "energy_category": energy_category} |
||
1438 | result.append(meta_result) |
||
1439 | |||
1440 | resp.body = json.dumps(result) |
||
1441 | |||
1442 | @staticmethod |
||
1443 | def on_post(req, resp, id_): |
||
1444 | """Handles POST requests""" |
||
1445 | try: |
||
1446 | raw_json = req.stream.read().decode('utf-8') |
||
1447 | except Exception as ex: |
||
1448 | raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) |
||
1449 | |||
1450 | if not id_.isdigit() or int(id_) <= 0: |
||
1451 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1452 | description='API.INVALID_TENANT_ID') |
||
1453 | |||
1454 | new_values = json.loads(raw_json) |
||
1455 | |||
1456 | if 'virtual_meter_id' not in new_values['data'].keys() or \ |
||
1457 | not isinstance(new_values['data']['virtual_meter_id'], int) or \ |
||
1458 | new_values['data']['virtual_meter_id'] <= 0: |
||
1459 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1460 | description='API.INVALID_VIRTUAL_METER_ID') |
||
1461 | virtual_meter_id = new_values['data']['virtual_meter_id'] |
||
1462 | |||
1463 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1464 | cursor = cnx.cursor() |
||
1465 | |||
1466 | cursor.execute(" SELECT name " |
||
1467 | " from tbl_tenants " |
||
1468 | " WHERE id = %s ", (id_,)) |
||
1469 | if cursor.fetchone() is None: |
||
1470 | cursor.close() |
||
1471 | cnx.disconnect() |
||
1472 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1473 | description='API.TENANT_NOT_FOUND') |
||
1474 | |||
1475 | cursor.execute(" SELECT name " |
||
1476 | " FROM tbl_virtual_meters " |
||
1477 | " WHERE id = %s ", (virtual_meter_id,)) |
||
1478 | if cursor.fetchone() is None: |
||
1479 | cursor.close() |
||
1480 | cnx.disconnect() |
||
1481 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1482 | description='API.VIRTUAL_METER_NOT_FOUND') |
||
1483 | |||
1484 | query = (" SELECT id " |
||
1485 | " FROM tbl_tenants_virtual_meters " |
||
1486 | " WHERE tenant_id = %s AND virtual_meter_id = %s") |
||
1487 | cursor.execute(query, (id_, virtual_meter_id,)) |
||
1488 | if cursor.fetchone() is not None: |
||
1489 | cursor.close() |
||
1490 | cnx.disconnect() |
||
1491 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', |
||
1492 | description='API.TENANT_VIRTUAL_METER_RELATION_EXISTED') |
||
1493 | |||
1494 | add_row = (" INSERT INTO tbl_tenants_virtual_meters (tenant_id, virtual_meter_id) " |
||
1495 | " VALUES (%s, %s) ") |
||
1496 | cursor.execute(add_row, (id_, virtual_meter_id,)) |
||
1497 | new_id = cursor.lastrowid |
||
1498 | cnx.commit() |
||
1499 | cursor.close() |
||
1500 | cnx.disconnect() |
||
1501 | |||
1502 | resp.status = falcon.HTTP_201 |
||
1503 | resp.location = '/tenants/' + str(id_) + '/virtualmeters/' + str(virtual_meter_id) |
||
1504 | |||
1505 | |||
1506 | View Code Duplication | class TenantVirtualMeterItem: |
|
1507 | @staticmethod |
||
1508 | def __init__(): |
||
1509 | pass |
||
1510 | |||
1511 | @staticmethod |
||
1512 | def on_options(req, resp, id_, mid): |
||
1513 | resp.status = falcon.HTTP_200 |
||
1514 | |||
1515 | @staticmethod |
||
1516 | def on_delete(req, resp, id_, mid): |
||
1517 | if not id_.isdigit() or int(id_) <= 0: |
||
1518 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1519 | description='API.INVALID_TENANT_ID') |
||
1520 | |||
1521 | if not mid.isdigit() or int(mid) <= 0: |
||
1522 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
1523 | description='API.INVALID_VIRTUAL_METER_ID') |
||
1524 | |||
1525 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
1526 | cursor = cnx.cursor() |
||
1527 | |||
1528 | cursor.execute(" SELECT name " |
||
1529 | " FROM tbl_tenants " |
||
1530 | " WHERE id = %s ", (id_,)) |
||
1531 | if cursor.fetchone() is None: |
||
1532 | cursor.close() |
||
1533 | cnx.disconnect() |
||
1534 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1535 | description='API.TENANT_NOT_FOUND') |
||
1536 | |||
1537 | cursor.execute(" SELECT name " |
||
1538 | " FROM tbl_virtual_meters " |
||
1539 | " WHERE id = %s ", (mid,)) |
||
1540 | if cursor.fetchone() is None: |
||
1541 | cursor.close() |
||
1542 | cnx.disconnect() |
||
1543 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1544 | description='API.VIRTUAL_METER_NOT_FOUND') |
||
1545 | |||
1546 | cursor.execute(" SELECT id " |
||
1547 | " FROM tbl_tenants_virtual_meters " |
||
1548 | " WHERE tenant_id = %s AND virtual_meter_id = %s ", (id_, mid)) |
||
1549 | if cursor.fetchone() is None: |
||
1550 | cursor.close() |
||
1551 | cnx.disconnect() |
||
1552 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
1553 | description='API.TENANT_VIRTUAL_METER_RELATION_NOT_FOUND') |
||
1554 | |||
1555 | cursor.execute(" DELETE FROM tbl_tenants_virtual_meters " |
||
1556 | " WHERE tenant_id = %s AND virtual_meter_id = %s ", (id_, mid)) |
||
1557 | cnx.commit() |
||
1558 | |||
1559 | cursor.close() |
||
1560 | cnx.disconnect() |
||
1561 | |||
1562 | resp.status = falcon.HTTP_204 |
||
1563 | |||
1565 |