From 447eb57202d62a1b954bc317d3647ce16179e93d Mon Sep 17 00:00:00 2001 From: "13621160019@163.com" <13621160019@163.com> Date: Sun, 12 Sep 2021 22:50:36 +0800 Subject: [PATCH] added aliyunsmsapi to api/core --- myems-api/MyEMS.postman_collection.json | 47 +++-- myems-api/app.py | 15 +- myems-api/core/aliyunsmsapi.py | 268 ++++++++++++++++++++++++ myems-api/core/gsmmodem.py | 215 ------------------- 4 files changed, 305 insertions(+), 240 deletions(-) create mode 100644 myems-api/core/aliyunsmsapi.py delete mode 100644 myems-api/core/gsmmodem.py diff --git a/myems-api/MyEMS.postman_collection.json b/myems-api/MyEMS.postman_collection.json index cf23dbdf..6b453506 100644 --- a/myems-api/MyEMS.postman_collection.json +++ b/myems-api/MyEMS.postman_collection.json @@ -582,6 +582,15 @@ } }, "response": [] + }, + { + "name": "New Request", + "request": { + "method": "GET", + "header": [], + "url": null + }, + "response": [] } ] }, @@ -2693,37 +2702,37 @@ ] }, { - "name": "GSM Modem", + "name": "Aliyun SMS API", "item": [ { - "name": "GET All GSM Modems", + "name": "GET All Aliyun SMS APIs", "request": { "method": "GET", "header": [], "url": { - "raw": "{{base_url}}/gsmmodems", + "raw": "{{base_url}}/aliyunsmsapis", "host": [ "{{base_url}}" ], "path": [ - "gsmmodems" + "aliyunsmsapis" ] } }, "response": [] }, { - "name": "GET a GSM Modem by ID", + "name": "GET an Aliyun SMS API by ID", "request": { "method": "GET", "header": [], "url": { - "raw": "{{base_url}}/gsmmodems/1", + "raw": "{{base_url}}/aliyunsmsapis/1", "host": [ "{{base_url}}" ], "path": [ - "gsmmodems", + "aliyunsmsapis", "1" ] } @@ -2731,38 +2740,42 @@ "response": [] }, { - "name": "POST Create New GSM Modem", + "name": "POST Create New Aliyun SMS API", "request": { "method": "POST", "header": [], "body": { "mode": "raw", - "raw": "{\"data\":{\"serial_port\":\"/dev/ttyS1\",\"baud_rate\":115200}}" + "raw": "{\"data\":{\"access_key_id\":\"xTAI5t8KUj8jXXXXXXXXXXXX\",\"access_key_secret\":\"fXXjFLA7GeXXXXXXXXXXXXXXXXXXXX\",\"endpoint\":\"https://dysmsapi.aliyuncs.com\",\"sign_name\":\"MYEMS\",\"template_code\":\"SMS_153055065\"}}" }, "url": { - "raw": "{{base_url}}/gsmmodems", + "raw": "{{base_url}}/aliyunsmsapis", "host": [ "{{base_url}}" ], "path": [ - "gsmmodems" + "aliyunsmsapis" ] } }, "response": [] }, { - "name": "PUT Update a GSM Modem", + "name": "PUT Update an Aliyun SMS API", "request": { "method": "PUT", "header": [], + "body": { + "mode": "raw", + "raw": "{\"data\":{\"access_key_id\":\"LTAI5t8KUj8jXXXXXXXXXXXX\",\"access_key_secret\":\"fXXjFLA7GeXXXXXXXXXXXXXXXXXXXX\",\"endpoint\":\"https://dysmsapi.aliyuncs.com\",\"sign_name\":\"MYEMS\",\"template_code\":\"SMS_153055065\"}}" + }, "url": { - "raw": "{{base_url}}/gsmmodems/1", + "raw": "{{base_url}}/aliyunsmsapis/1", "host": [ "{{base_url}}" ], "path": [ - "gsmmodems", + "aliyunsmsapis", "1" ] } @@ -2770,17 +2783,17 @@ "response": [] }, { - "name": "DELETE a GSM Modem by ID", + "name": "DELETE an Aliyun SMS API by ID", "request": { "method": "DELETE", "header": [], "url": { - "raw": "{{base_url}}/gsmmodems/2", + "raw": "{{base_url}}/aliyunsmsapis/2", "host": [ "{{base_url}}" ], "path": [ - "gsmmodems", + "aliyunsmsapis", "2" ] } diff --git a/myems-api/app.py b/myems-api/app.py index 458da0d1..406bbf4a 100644 --- a/myems-api/app.py +++ b/myems-api/app.py @@ -1,8 +1,8 @@ import falcon from falcon_cors import CORS from falcon_multipart.middleware import MultipartMiddleware -from core import energyflowdiagram, privilege, textmessage, distributioncircuit, virtualmeter, \ - costcenter, point, knowledgefile, meter, gsmmodem, tariff, user, storetype, timezone, \ +from core import aliyunsmsapi, energyflowdiagram, privilege, textmessage, distributioncircuit, virtualmeter, \ + costcenter, point, knowledgefile, meter, tariff, user, storetype, timezone, \ costfile, offlinemeterfile, version, contact, emailserver, combinedequipment, datasource, equipment, tenant, \ shopfloor, webmessage, distributionsystem, store, emailmessage, tenanttype, wechatmessage, space, gateway, \ offlinemeter, rule, energycategory, sensor, energyitem, notification, menu @@ -99,9 +99,13 @@ api = falcon.API(middleware=[cors.middleware, MultipartMiddleware()]) ######################################################################################################################## -# Routes for System Configuration +# Routes for System Core ######################################################################################################################## +api.add_route('/aliyunsmsapis', + aliyunsmsapi.AliyunSMSAPICollection()) +api.add_route('/aliyunsmsapis/{id_}', + aliyunsmsapi.AliyunSMSAPIItem()) api.add_route('/combinedequipments', combinedequipment.CombinedEquipmentCollection()) api.add_route('/combinedequipments/{id_}', @@ -232,11 +236,6 @@ api.add_route('/gateways/{id_}', api.add_route('/gateways/{id_}/datasources', gateway.GatewayDataSourceCollection()) -api.add_route('/gsmmodems', - gsmmodem.GSMModemCollection()) -api.add_route('/gsmmodems/{id_}', - gsmmodem.GSMModemItem()) - api.add_route('/knowledgefiles', knowledgefile.KnowledgeFileCollection()) api.add_route('/knowledgefiles/{id_}', diff --git a/myems-api/core/aliyunsmsapi.py b/myems-api/core/aliyunsmsapi.py new file mode 100644 index 00000000..c9c329cd --- /dev/null +++ b/myems-api/core/aliyunsmsapi.py @@ -0,0 +1,268 @@ +import falcon +import json +import mysql.connector +import config +from core.userlogger import user_logger + + +class AliyunSMSAPICollection: + @staticmethod + def __init__(): + """Initializes AliyunSMSAPICollection""" + pass + + @staticmethod + def on_options(req, resp): + resp.status = falcon.HTTP_200 + + @staticmethod + def on_get(req, resp): + cnx = mysql.connector.connect(**config.myems_fdd_db) + cursor = cnx.cursor() + + query = (" SELECT id, access_key_id, access_key_secret, endpoint, sign_name, template_code " + " FROM tbl_aliyun_sms_api ") + cursor.execute(query) + rows = cursor.fetchall() + cursor.close() + cnx.disconnect() + + result = list() + if rows is not None and len(rows) > 0: + for row in rows: + meta_result = {"id": row[0], + "access_key_id": row[1], + "access_key_secret": row[2], + "endpoint": row[3], + "sign_name": row[4], + "template_code": row[5]} + result.append(meta_result) + + resp.body = json.dumps(result) + + @staticmethod + @user_logger + def on_post(req, resp): + """Handles POST requests""" + try: + raw_json = req.stream.read().decode('utf-8') + except Exception as ex: + raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) + + new_values = json.loads(raw_json) + + if 'access_key_id' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['access_key_id'], str) or \ + len(str.strip(new_values['data']['access_key_id'])) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_ID') + access_key_id = str.strip(new_values['data']['access_key_id']) + + if 'access_key_secret' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['access_key_secret'], str) or \ + len(new_values['data']['access_key_secret']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_SECRET') + access_key_secret = new_values['data']['access_key_secret'] + + if 'endpoint' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['endpoint'], str) or \ + len(new_values['data']['endpoint']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ENDPOINT') + endpoint = new_values['data']['endpoint'] + + if 'sign_name' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['sign_name'], str) or \ + len(new_values['data']['sign_name']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_SIGN_NAME') + sign_name = new_values['data']['sign_name'] + + if 'template_code' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['template_code'], str) or \ + len(new_values['data']['template_code']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_TEMPLATE_CODE') + template_code = new_values['data']['template_code'] + + cnx = mysql.connector.connect(**config.myems_fdd_db) + cursor = cnx.cursor() + + cursor.execute(" SELECT id " + " FROM tbl_aliyun_sms_api " + " WHERE access_key_id = %s ", (access_key_id,)) + if cursor.fetchone() is not None: + cursor.close() + cnx.disconnect() + raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', + description='API.ALIYUN_SMS_API_ACCESS_KEY_ID_IS_ALREADY_IN_USE') + + add_value = (" INSERT INTO tbl_aliyun_sms_api " + " (access_key_id, access_key_secret, endpoint, sign_name, template_code) " + " VALUES (%s, %s, %s, %s, %s) ") + cursor.execute(add_value, (access_key_id, + access_key_secret, + endpoint, + sign_name, + template_code)) + new_id = cursor.lastrowid + cnx.commit() + cursor.close() + cnx.disconnect() + + resp.status = falcon.HTTP_201 + resp.location = '/aliyunsmsapis/' + str(new_id) + + +class AliyunSMSAPIItem: + @staticmethod + def __init__(): + """Initializes AliyunSMSAPIItem""" + pass + + @staticmethod + def on_options(req, resp, id_): + resp.status = falcon.HTTP_200 + + @staticmethod + def on_get(req, resp, id_): + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, '400 Bad Request') + + cnx = mysql.connector.connect(**config.myems_fdd_db) + cursor = cnx.cursor() + + query = (" SELECT id, access_key_id, access_key_secret, endpoint, sign_name, template_code " + " FROM tbl_aliyun_sms_api " + " WHERE id = %s ") + cursor.execute(query, (id_,)) + row = cursor.fetchone() + cursor.close() + cnx.disconnect() + if row is None: + raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND') + + result = {"id": row[0], + "access_key_id": row[1], + "access_key_secret": row[2], + "endpoint": row[3], + "sign_name": row[4], + "template_code": row[5]} + resp.body = json.dumps(result) + + @staticmethod + @user_logger + def on_delete(req, resp, id_): + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ID') + + cnx = mysql.connector.connect(**config.myems_fdd_db) + cursor = cnx.cursor() + + cursor.execute(" SELECT access_key_id " + " FROM tbl_aliyun_sms_api " + " WHERE id = %s ", (id_,)) + if cursor.fetchone() is None: + cursor.close() + cnx.disconnect() + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.ALIYUN_SMS_API_NOT_FOUND') + + cursor.execute(" DELETE FROM tbl_aliyun_sms_api WHERE id = %s ", (id_,)) + cnx.commit() + + cursor.close() + cnx.disconnect() + + resp.status = falcon.HTTP_204 + + @staticmethod + @user_logger + def on_put(req, resp, id_): + """Handles PUT requests""" + try: + raw_json = req.stream.read().decode('utf-8') + except Exception as ex: + raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) + + if not id_.isdigit() or int(id_) <= 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ID') + + new_values = json.loads(raw_json) + + if 'access_key_id' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['access_key_id'], str) or \ + len(str.strip(new_values['data']['access_key_id'])) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_ID') + access_key_id = str.strip(new_values['data']['access_key_id']) + + if 'access_key_secret' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['access_key_secret'], str) or \ + len(new_values['data']['access_key_secret']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ACCESS_KEY_SECRET') + access_key_secret = new_values['data']['access_key_secret'] + + if 'endpoint' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['endpoint'], str) or \ + len(new_values['data']['endpoint']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_ENDPOINT') + endpoint = new_values['data']['endpoint'] + + if 'sign_name' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['sign_name'], str) or \ + len(new_values['data']['sign_name']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_SIGN_NAME') + sign_name = new_values['data']['sign_name'] + + if 'template_code' not in new_values['data'].keys() or \ + not isinstance(new_values['data']['template_code'], str) or \ + len(new_values['data']['template_code']) == 0: + raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', + description='API.INVALID_ALIYUN_SMS_API_TEMPLATE_CODE') + template_code = new_values['data']['template_code'] + + cnx = mysql.connector.connect(**config.myems_fdd_db) + cursor = cnx.cursor() + + cursor.execute(" SELECT access_key_id " + " FROM tbl_aliyun_sms_api " + " WHERE id = %s ", + (id_,)) + if cursor.fetchone() is None: + cursor.close() + cnx.disconnect() + raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', + description='API.ALIYUN_SMS_API_NOT_FOUND') + + cursor.execute(" SELECT access_key_id " + " FROM tbl_aliyun_sms_api " + " WHERE access_key_id = %s AND id != %s ", (access_key_id, id_)) + if cursor.fetchone() is not None: + cursor.close() + cnx.disconnect() + raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', + description='API.ALIYUN_SMS_API_ACCESS_KEY_ID_IS_ALREADY_IN_USE') + + update_row = (" UPDATE tbl_aliyun_sms_api " + " SET access_key_id = %s, access_key_secret = %s, endpoint = %s, sign_name = %s, " + " template_code = %s " + " WHERE id = %s ") + cursor.execute(update_row, (access_key_id, + access_key_secret, + endpoint, + sign_name, + template_code, + id_,)) + cnx.commit() + + cursor.close() + cnx.disconnect() + + resp.status = falcon.HTTP_200 diff --git a/myems-api/core/gsmmodem.py b/myems-api/core/gsmmodem.py deleted file mode 100644 index d3d45cb8..00000000 --- a/myems-api/core/gsmmodem.py +++ /dev/null @@ -1,215 +0,0 @@ -import falcon -import json -import mysql.connector -import config -from core.userlogger import user_logger - - -class GSMModemCollection: - @staticmethod - def __init__(): - """Initializes GSMModemCollection""" - pass - - @staticmethod - def on_options(req, resp): - resp.status = falcon.HTTP_200 - - @staticmethod - def on_get(req, resp): - cnx = mysql.connector.connect(**config.myems_fdd_db) - cursor = cnx.cursor() - - query = (" SELECT id, serial_port, baud_rate " - " FROM tbl_gsm_modems ") - cursor.execute(query) - rows = cursor.fetchall() - cursor.close() - cnx.disconnect() - - result = list() - if rows is not None and len(rows) > 0: - for row in rows: - meta_result = {"id": row[0], - "serial_port": row[1], - "baud_rate": row[2]} - result.append(meta_result) - - resp.body = json.dumps(result) - - @staticmethod - @user_logger - def on_post(req, resp): - """Handles POST requests""" - try: - raw_json = req.stream.read().decode('utf-8') - except Exception as ex: - raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex) - - new_values = json.loads(raw_json) - - if 'serial_port' not in new_values['data'].keys() or \ - not isinstance(new_values['data']['serial_port'], str) or \ - len(str.strip(new_values['data']['serial_port'])) == 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_SERIAL_PORT') - - serial_port = str.strip(new_values['data']['serial_port']) - - if 'baud_rate' not in new_values['data'].keys() or \ - not isinstance(new_values['data']['baud_rate'], int) or \ - new_values['data']['baud_rate'] <= 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_BAUD_RATE') - baud_rate = float(new_values['data']['baud_rate']) - - cnx = mysql.connector.connect(**config.myems_fdd_db) - cursor = cnx.cursor() - - cursor.execute(" SELECT id " - " FROM tbl_gsm_modems " - " WHERE serial_port = %s ", (serial_port,)) - if cursor.fetchone() is not None: - cursor.close() - cnx.disconnect() - raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', - description='API.GSM_MODEM_SERIAL_PORT_IS_ALREADY_IN_USE') - - add_value = (" INSERT INTO tbl_gsm_modems " - " (serial_port, baud_rate) " - " VALUES (%s, %s) ") - cursor.execute(add_value, (serial_port, - baud_rate)) - new_id = cursor.lastrowid - cnx.commit() - cursor.close() - cnx.disconnect() - - resp.status = falcon.HTTP_201 - resp.location = '/gsmmodems/' + str(new_id) - - -class GSMModemItem: - @staticmethod - def __init__(): - """Initializes GSMModemItem""" - pass - - @staticmethod - def on_options(req, resp, id_): - resp.status = falcon.HTTP_200 - - @staticmethod - def on_get(req, resp, id_): - if not id_.isdigit() or int(id_) <= 0: - raise falcon.HTTPError(falcon.HTTP_400, '400 Bad Request') - - cnx = mysql.connector.connect(**config.myems_fdd_db) - cursor = cnx.cursor() - - query = (" SELECT id, serial_port, baud_rate " - " FROM tbl_gsm_modems " - " WHERE id = %s ") - cursor.execute(query, (id_,)) - row = cursor.fetchone() - cursor.close() - cnx.disconnect() - if row is None: - raise falcon.HTTPError(falcon.HTTP_404, 'API.NOT_FOUND') - - result = {"id": row[0], - "serial_port": row[1], - "baud_rate": row[2]} - resp.body = json.dumps(result) - - @staticmethod - @user_logger - def on_delete(req, resp, id_): - if not id_.isdigit() or int(id_) <= 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_GSM_MODEM_ID') - - cnx = mysql.connector.connect(**config.myems_fdd_db) - cursor = cnx.cursor() - - cursor.execute(" SELECT serial_port " - " FROM tbl_gsm_modems " - " WHERE id = %s ", (id_,)) - if cursor.fetchone() is None: - cursor.close() - cnx.disconnect() - raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', - description='API.GSM_MODEM_NOT_FOUND') - - cursor.execute(" DELETE FROM tbl_gsm_modems WHERE id = %s ", (id_,)) - cnx.commit() - - cursor.close() - cnx.disconnect() - - resp.status = falcon.HTTP_204 - - @staticmethod - @user_logger - def on_put(req, resp, id_): - """Handles PUT requests""" - try: - raw_json = req.stream.read().decode('utf-8') - except Exception as ex: - raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex) - - if not id_.isdigit() or int(id_) <= 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_GSM_MODEM_ID') - - new_values = json.loads(raw_json) - - if 'serial_port' not in new_values['data'].keys() or \ - not isinstance(new_values['data']['serial_port'], str) or \ - len(str.strip(new_values['data']['serial_port'])) == 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_SERIAL_PORT') - - serial_port = str.strip(new_values['data']['serial_port']) - - if 'baud_rate' not in new_values['data'].keys() or \ - not isinstance(new_values['data']['baud_rate'], int) or \ - new_values['data']['baud_rate'] <= 0: - raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST', - description='API.INVALID_BAUD_RATE') - baud_rate = float(new_values['data']['baud_rate']) - - cnx = mysql.connector.connect(**config.myems_fdd_db) - cursor = cnx.cursor() - - cursor.execute(" SELECT serial_port " - " FROM tbl_gsm_modems " - " WHERE id = %s ", - (id_,)) - if cursor.fetchone() is None: - cursor.close() - cnx.disconnect() - raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND', - description='API.GSM_MODEM_NOT_FOUND') - - cursor.execute(" SELECT serial_port " - " FROM tbl_gsm_modems " - " WHERE serial_port = %s AND id != %s ", (serial_port, id_)) - if cursor.fetchone() is not None: - cursor.close() - cnx.disconnect() - raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST', - description='API.GSM_MODEM_SERIAL_PORT_IS_ALREADY_IN_USE') - - update_row = (" UPDATE tbl_gsm_modems " - " SET serial_port = %s, baud_rate = %s " - " WHERE id = %s ") - cursor.execute(update_row, (serial_port, - baud_rate, - id_,)) - cnx.commit() - - cursor.close() - cnx.disconnect() - - resp.status = falcon.HTTP_200