myems /
myems-api
| 1 | import falcon |
||
| 2 | import simplejson as json |
||
| 3 | import mysql.connector |
||
| 4 | import config |
||
| 5 | import uuid |
||
| 6 | from datetime import datetime |
||
| 7 | |||
| 8 | |||
| 9 | class GatewayCollection: |
||
| 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() |
||
| 22 | |||
| 23 | query = (" SELECT id, name, uuid, token, last_seen_datetime_utc " |
||
| 24 | " FROM tbl_gateways " |
||
| 25 | " ORDER BY id ") |
||
| 26 | cursor.execute(query) |
||
| 27 | rows = cursor.fetchall() |
||
| 28 | cursor.close() |
||
| 29 | cnx.disconnect() |
||
| 30 | |||
| 31 | result = list() |
||
| 32 | now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None) |
||
| 33 | View Code Duplication | if rows is not None and len(rows) > 0: |
|
|
0 ignored issues
–
show
Duplication
introduced
by
Loading history...
|
|||
| 34 | for row in rows: |
||
| 35 | last_seen_time = row[4] |
||
| 36 | if last_seen_time is not None and (now - last_seen_time).total_seconds() > 5 * 60: |
||
| 37 | status = "online" |
||
| 38 | else: |
||
| 39 | status = "offline" |
||
| 40 | meta_result = {"id": row[0], "name": row[1], "uuid": row[2], |
||
| 41 | "token": row[3], |
||
| 42 | "last_seen_datetime": row[4].timestamp() * 1000 if isinstance(row[4], |
||
| 43 | datetime) else None, |
||
| 44 | "status": status} |
||
| 45 | result.append(meta_result) |
||
| 46 | |||
| 47 | resp.body = json.dumps(result) |
||
| 48 | |||
| 49 | View Code Duplication | @staticmethod |
|
|
0 ignored issues
–
show
|
|||
| 50 | def on_post(req, resp): |
||
| 51 | """Handles POST requests""" |
||
| 52 | try: |
||
| 53 | raw_json = req.stream.read().decode('utf-8') |
||
| 54 | except Exception as ex: |
||
| 55 | raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) |
||
| 56 | |||
| 57 | new_values = json.loads(raw_json, encoding='utf-8') |
||
| 58 | |||
| 59 | if 'name' not in new_values['data'].keys() or \ |
||
| 60 | not isinstance(new_values['data']['name'], str) or \ |
||
| 61 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 62 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 63 | description='API.INVALID_GATEWAY_NAME') |
||
| 64 | name = str.strip(new_values['data']['name']) |
||
| 65 | |||
| 66 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 67 | cursor = cnx.cursor() |
||
| 68 | |||
| 69 | cursor.execute(" SELECT name " |
||
| 70 | " FROM tbl_gateways " |
||
| 71 | " WHERE name = %s ", (name,)) |
||
| 72 | if cursor.fetchone() is not None: |
||
| 73 | cursor.close() |
||
| 74 | cnx.disconnect() |
||
| 75 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
| 76 | description='API.GATEWAY_NAME_IS_ALREADY_IN_USE') |
||
| 77 | |||
| 78 | add_values = (" INSERT INTO tbl_gateways (name, uuid, token) " |
||
| 79 | " VALUES (%s, %s, %s) ") |
||
| 80 | cursor.execute(add_values, (name, |
||
| 81 | str(uuid.uuid4()), |
||
| 82 | str(uuid.uuid4()))) |
||
| 83 | new_id = cursor.lastrowid |
||
| 84 | cnx.commit() |
||
| 85 | cursor.close() |
||
| 86 | cnx.disconnect() |
||
| 87 | |||
| 88 | resp.status = falcon.HTTP_201 |
||
| 89 | resp.location = '/gateways/' + str(new_id) |
||
| 90 | |||
| 91 | |||
| 92 | class GatewayItem: |
||
| 93 | @staticmethod |
||
| 94 | def __init__(): |
||
| 95 | pass |
||
| 96 | |||
| 97 | @staticmethod |
||
| 98 | def on_options(req, resp, id_): |
||
| 99 | resp.status = falcon.HTTP_200 |
||
| 100 | |||
| 101 | @staticmethod |
||
| 102 | def on_get(req, resp, id_): |
||
| 103 | if not id_.isdigit() or int(id_) <= 0: |
||
| 104 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 105 | description='API.INVALID_GATEWAY_ID') |
||
| 106 | |||
| 107 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 108 | cursor = cnx.cursor() |
||
| 109 | |||
| 110 | query = (" SELECT id, name, uuid, token, last_seen_datetime_utc " |
||
| 111 | " FROM tbl_gateways " |
||
| 112 | " WHERE id =%s ") |
||
| 113 | cursor.execute(query, (id_,)) |
||
| 114 | row = cursor.fetchone() |
||
| 115 | cursor.close() |
||
| 116 | cnx.disconnect() |
||
| 117 | if row is None: |
||
| 118 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 119 | description='API.GATEWAY_NOT_FOUND') |
||
| 120 | |||
| 121 | now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None) |
||
| 122 | last_seen_time = row[4] |
||
| 123 | if last_seen_time is not None and (now - last_seen_time).total_seconds() > 5 * 60: |
||
| 124 | status = "online" |
||
| 125 | else: |
||
| 126 | status = "offline" |
||
| 127 | |||
| 128 | result = {"id": row[0], "name": row[1], "uuid": row[2], |
||
| 129 | "token": row[3], |
||
| 130 | "last_seen_datetime": row[4].timestamp()*1000 if isinstance(row[4], datetime) else None, |
||
| 131 | "status": status} |
||
| 132 | |||
| 133 | resp.body = json.dumps(result) |
||
| 134 | |||
| 135 | @staticmethod |
||
| 136 | def on_delete(req, resp, id_): |
||
| 137 | if not id_.isdigit() or int(id_) <= 0: |
||
| 138 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 139 | description='API.INVALID_GATEWAY_ID') |
||
| 140 | |||
| 141 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 142 | cursor = cnx.cursor() |
||
| 143 | |||
| 144 | cursor.execute(" SELECT name " |
||
| 145 | " FROM tbl_gateways " |
||
| 146 | " WHERE id = %s ", (id_,)) |
||
| 147 | if cursor.fetchone() is None: |
||
| 148 | cursor.close() |
||
| 149 | cnx.disconnect() |
||
| 150 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 151 | description='API.GATEWAY_NOT_FOUND') |
||
| 152 | |||
| 153 | # check if this gateway is being used by any data sources |
||
| 154 | cursor.execute(" SELECT name " |
||
| 155 | " FROM tbl_data_sources " |
||
| 156 | " WHERE gateway_id = %s ", |
||
| 157 | " LIMIT 1 ", |
||
| 158 | (id_,)) |
||
| 159 | if cursor.fetchone() is not None: |
||
| 160 | cursor.close() |
||
| 161 | cnx.disconnect() |
||
| 162 | raise falcon.HTTPError(falcon.HTTP_400, |
||
| 163 | title='API.BAD_REQUEST', |
||
| 164 | description='API.THERE_IS_RELATION_WITH_DATA_SOURCES') |
||
| 165 | |||
| 166 | cursor.execute(" DELETE FROM tbl_gateways WHERE id = %s ", (id_,)) |
||
| 167 | cnx.commit() |
||
| 168 | |||
| 169 | cursor.close() |
||
| 170 | cnx.disconnect() |
||
| 171 | resp.status = falcon.HTTP_204 |
||
| 172 | |||
| 173 | View Code Duplication | @staticmethod |
|
|
0 ignored issues
–
show
|
|||
| 174 | def on_put(req, resp, id_): |
||
| 175 | """Handles PUT requests""" |
||
| 176 | try: |
||
| 177 | raw_json = req.stream.read().decode('utf-8') |
||
| 178 | except Exception as ex: |
||
| 179 | raise falcon.HTTPError(falcon.HTTP_400, 'API.ERROR', ex) |
||
| 180 | |||
| 181 | if not id_.isdigit() or int(id_) <= 0: |
||
| 182 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 183 | description='API.INVALID_GATEWAY_ID') |
||
| 184 | |||
| 185 | new_values = json.loads(raw_json, encoding='utf-8') |
||
| 186 | |||
| 187 | if 'name' not in new_values['data'].keys() or \ |
||
| 188 | not isinstance(new_values['data']['name'], str) or \ |
||
| 189 | len(str.strip(new_values['data']['name'])) == 0: |
||
| 190 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 191 | description='API.INVALID_GATEWAY_NAME') |
||
| 192 | name = str.strip(new_values['data']['name']) |
||
| 193 | |||
| 194 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 195 | cursor = cnx.cursor() |
||
| 196 | |||
| 197 | cursor.execute(" SELECT name " |
||
| 198 | " FROM tbl_gateways " |
||
| 199 | " WHERE id = %s ", (id_,)) |
||
| 200 | if cursor.fetchone() is None: |
||
| 201 | cursor.close() |
||
| 202 | cnx.disconnect() |
||
| 203 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 204 | description='API.GATEWAY_NOT_FOUND') |
||
| 205 | |||
| 206 | cursor.execute(" SELECT name " |
||
| 207 | " FROM tbl_gateways " |
||
| 208 | " WHERE name = %s AND id != %s ", (name, id_)) |
||
| 209 | if cursor.fetchone() is not None: |
||
| 210 | cursor.close() |
||
| 211 | cnx.disconnect() |
||
| 212 | raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', |
||
| 213 | description='API.GATEWAY_NAME_IS_ALREADY_IN_USE') |
||
| 214 | |||
| 215 | update_row = (" UPDATE tbl_gateways " |
||
| 216 | " SET name = %s " |
||
| 217 | " WHERE id = %s ") |
||
| 218 | cursor.execute(update_row, (name, |
||
| 219 | id_,)) |
||
| 220 | cnx.commit() |
||
| 221 | |||
| 222 | cursor.close() |
||
| 223 | cnx.disconnect() |
||
| 224 | |||
| 225 | resp.status = falcon.HTTP_200 |
||
| 226 | |||
| 227 | |||
| 228 | class GatewayDataSourceCollection: |
||
| 229 | @staticmethod |
||
| 230 | def __init__(): |
||
| 231 | pass |
||
| 232 | |||
| 233 | @staticmethod |
||
| 234 | def on_options(req, resp): |
||
| 235 | resp.status = falcon.HTTP_200 |
||
| 236 | |||
| 237 | @staticmethod |
||
| 238 | def on_get(req, resp, id_): |
||
| 239 | if not id_.isdigit() or int(id_) <= 0: |
||
| 240 | raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', |
||
| 241 | description='API.INVALID_GATEWAY_ID') |
||
| 242 | |||
| 243 | cnx = mysql.connector.connect(**config.myems_system_db) |
||
| 244 | cursor = cnx.cursor() |
||
| 245 | |||
| 246 | cursor.execute(" SELECT name " |
||
| 247 | " FROM tbl_gateways " |
||
| 248 | " WHERE id = %s ", (id_,)) |
||
| 249 | if cursor.fetchone() is None: |
||
| 250 | cursor.close() |
||
| 251 | cnx.disconnect() |
||
| 252 | raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', |
||
| 253 | description='API.GATEWAY_NOT_FOUND') |
||
| 254 | |||
| 255 | result = list() |
||
| 256 | query_data_source = (" SELECT id, name, uuid, " |
||
| 257 | " protocol, connection, last_seen_datetime_utc " |
||
| 258 | " FROM tbl_data_sources " |
||
| 259 | " WHERE gateway_id = %s " |
||
| 260 | " ORDER BY name ") |
||
| 261 | cursor.execute(query_data_source, (id_,)) |
||
| 262 | rows_data_source = cursor.fetchall() |
||
| 263 | now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=None) |
||
| 264 | View Code Duplication | if rows_data_source is not None and len(rows_data_source) > 0: |
|
|
0 ignored issues
–
show
|
|||
| 265 | for row in rows_data_source: |
||
| 266 | last_seen_time = row[5] |
||
| 267 | if last_seen_time is not None and (now - last_seen_time).total_seconds() > 5 * 60: |
||
| 268 | status = "online" |
||
| 269 | else: |
||
| 270 | status = "offline" |
||
| 271 | meta_result = {"id": row[0], |
||
| 272 | "name": row[1], |
||
| 273 | "uuid": row[2], |
||
| 274 | "protocol": row[3], |
||
| 275 | "connection": row[4], |
||
| 276 | "last_seen_datetime": row[5].timestamp()*1000 if isinstance(row[5], datetime) else None, |
||
| 277 | "status": status} |
||
| 278 | result.append(meta_result) |
||
| 279 | |||
| 280 | cursor.close() |
||
| 281 | cnx.disconnect() |
||
| 282 | resp.body = json.dumps(result) |
||
| 283 | |||
| 284 |