From 209fcd340726fb922b34d502c138e19f7ee66de0 Mon Sep 17 00:00:00 2001 From: Ashwin Ginoria Date: Tue, 16 Jun 2020 16:31:53 +0530 Subject: [PATCH 1/2] Server (#3) * Connection should be outside except -_- * Added Table name to url instead of arument and Blkified scripts (#2) Signed-off-by: AshwinGinoria --- app.py | 4 +-- dbsetup.py | 49 +++++++++++++++------------- schema.sql | 3 +- server/__init__.py | 35 ++++++++++---------- server/db.py | 81 ++++++++++++++++++++++++++-------------------- 5 files changed, 94 insertions(+), 78 deletions(-) diff --git a/app.py b/app.py index 4988832..9642c65 100644 --- a/app.py +++ b/app.py @@ -1,4 +1,4 @@ from server import app -if __name__ == '__main__': - app.run(debug=True) \ No newline at end of file +if __name__ == "__main__": + app.run(debug=True) diff --git a/dbsetup.py b/dbsetup.py index efa27b1..7e6ced0 100644 --- a/dbsetup.py +++ b/dbsetup.py @@ -1,7 +1,7 @@ -''' +""" This is mysql development env setup file. Just run it once. -''' +""" import os import getpass @@ -12,39 +12,42 @@ mysql_config = dict() -dbname = 'SG_TMS' +dbname = "SG_TMS" dev_path = os.getcwd() try: - - mysql_config = json.loads(open(dev_path+'/mysql_config.json').read()) + + mysql_config = json.loads(open(dev_path + "/mysql_config.json").read()) except FileNotFoundError: - print('`mysql_config.json` is not present in your development env.\nSo we have to get your mysql authentication first') + print( + "`mysql_config.json` is not present in your development env.\nSo we have to get your mysql authentication first" + ) + + mysql_config["user"] = input("Enter your mysql Username (root): ") + + if mysql_config["user"].lower() in ["y", "\n", ""]: + mysql_config["user"] = "root" + + mysql_config["password"] = getpass.getpass( + prompt=f"Enter your mysql password for {mysql_config['user']} :" + ) - - mysql_config['user'] = input('Enter your mysql Username (root): ') - - if mysql_config['user'].lower() in ['y', '\n', '']: - mysql_config['user'] = 'root' + mysql_config["host"] = input("Enter your mysql hostname (localhost): ") - mysql_config['password'] = getpass.getpass(prompt=f"Enter your mysql password for {mysql_config['user']} :") - - mysql_config['host'] = input('Enter your mysql hostname (localhost): ') - - if mysql_config['host'].lower() in ['y', '\n', '']: - mysql_config['host'] = 'localhost' + if mysql_config["host"].lower() in ["y", "\n", ""]: + mysql_config["host"] = "localhost" - mysql_connection = connector.connect(**mysql_config) +mysql_connection = connector.connect(**mysql_config) - mycursor = mysql_connection.cursor() +mycursor = mysql_connection.cursor() - with open(os.getcwd()+'/schema.sql') as f: - mycursor.execute(f.read(), multi=True) +with open(os.getcwd() + "/schema.sql") as f: + mycursor.execute(f.read(), multi=True) - json.dump(mysql_config,open(dev_path+'/mysql_config.json', 'w'), indent=4) +json.dump(mysql_config, open(dev_path + "/mysql_config.json", "w"), indent=4) -__all__ = [] \ No newline at end of file +__all__ = [] diff --git a/schema.sql b/schema.sql index 5809940..f6f1252 100644 --- a/schema.sql +++ b/schema.sql @@ -18,7 +18,8 @@ CREATE TABLE `Consignor_Consignee` ( `Name` varchar(50) NOT NULL, `Contact` varchar(50) NOT NULL, `Address` varchar(50) NOT NULL, - `Email` varchar(50) NOT NULL, + `Email` varchar(50) DEFAULT NULL, + `GST_Number` varchar(15) NOT NULL UNIQUE, PRIMARY KEY (`ID`) ); diff --git a/server/__init__.py b/server/__init__.py index 183e0cf..aae982d 100644 --- a/server/__init__.py +++ b/server/__init__.py @@ -13,50 +13,51 @@ parser = reqparse.RequestParser() -parser.add_argument('data', action='append') -parser.add_argument('table_name') +parser.add_argument("data", action="append") def insert_arg_parse(): args = parser.parse_args() table_datas = [] - for string_data in args['data']: + for string_data in args["data"]: table_data = json.loads(string_data) table_datas.append(table_data) - + return table_datas class base(Resource): + # to_disp : dict of table columns with val: true for + # cols to be displayed + # eg to_disp = {'col1' = True, 'col2' = False, col3 = 'True'} + def get(self, table_name): + to_disp = insert_arg_parse()[0] - def get(self): - table_name = parser.parse_args()['table_name'] - response = {'result':show(table_name)} + response = {'result':show(table_name, to_disp)} response = jsonify(response) response.status_code = 202 return response - - - def post(self): - + + def post(self, table_name): + table_datas = insert_arg_parse() - response = jsonify({'reason':'bad-request'}) + response = jsonify({"reason": "bad-request"}) response.status_code = 400 try: - insert(table_datas) - response = jsonify({'reason':'success'}) + insert(table_name, table_datas) + response = jsonify({"reason": "success"}) response.status_code = 202 except PrimaryKeyAlreadyExistsError: - response = jsonify({'reason':'primary-key-already-exists'}) + response = jsonify({"reason": "primary-key-already-exists"}) response.status_code = 409 return response -api.add_resource(base, '/') +api.add_resource(base, "/") -__all__ = [app, api] \ No newline at end of file +__all__ = [app, api] diff --git a/server/db.py b/server/db.py index eb3748b..8ef3a3d 100644 --- a/server/db.py +++ b/server/db.py @@ -6,69 +6,80 @@ dev_path = os.getcwd() -mysql_config = json.loads(open(dev_path+'/mysql_config.json').read()) +mysql_config = json.loads(open(dev_path + "/mysql_config.json").read()) -mysql_config['database'] = 'SG_TMS' +mysql_config["database"] = "SG_TMS" connection = connector.connect(**mysql_config) class PrimaryKeyAlreadyExistsError(connector.Error): - ''' + """ raises when you are trying to insert a tuple whose primary key is already present int the database. - ''' - pass + """ + pass -def insert_one(table_data): - ''' - table_data : datatype - dict(table_name: string, value: dict) - ''' +def insert_one(table_name, table_data): - table_name = table_data['table_name'] - value = table_data['value'] + value = table_data cursor = connection.cursor() - + try: - cursor.execute(f''' + cursor.execute( + f""" INSERT INTO {table_name} ({", ".join(list(value.keys()))}) VALUES ({", ".join(list(value.values()))}); - ''') - + """ + ) + except connector.Error as err: - if err.errno == 1062: - raise PrimaryKeyAlreadyExistsError('The `city_id` you are trying to insert is already present in the table.') - + print(err) + finally: connection.commit() cursor.close() -def insert(table_datas): - - ''' - inserts tuple in databases. - this is separated from insert_one because of future error handling if one table for eg. - we are able to insert in one table and other table results in insertion error. +def insert(table_name, table_datas): - table_datas : list(table_data) - ''' - for table_data in table_datas: - insert_one(table_data) + insert_one(table_name, table_data) -def show(table_name): +def show(table_name, to_disp=None): cursor = connection.cursor() - cursor.execute(f''' - SELECT * FROM {table_name}; - ''') + + columns = [] + for key in to_disp.keys(): + if to_disp[key] == True: + columns.append(key) + + if columns == []: + cursor.execute( + f""" + SELECT * FROM {table_name}; + """ + ) + else: + cursor.execute( + f""" + SELECT {", ".join(columns)} FROM {table_name}; + """ + ) + result = cursor.fetchall() cursor.close() - return result - -__all__ = [insert, connection, dev_path, mysql_config, PrimaryKeyAlreadyExistsError, show] + return result +__all__ = [ + insert, + connection, + dev_path, + mysql_config, + PrimaryKeyAlreadyExistsError, + show, +] From 67fc5fca28b5f5b623f654ae687f3af301ac4b07 Mon Sep 17 00:00:00 2001 From: Ashwin Ginoria Date: Wed, 17 Jun 2020 00:38:55 +0530 Subject: [PATCH 2/2] Changed schema.sql (#4) --- schema.sql | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/schema.sql b/schema.sql index f6f1252..405f1a7 100644 --- a/schema.sql +++ b/schema.sql @@ -5,12 +5,11 @@ CREATE DATABASE `SG_TMS`; USE `SG_TMS`; CREATE TABLE `Vehicle` ( - `Vehicle_ID` int NOT NULL AUTO_INCREMENT, - `Vehicle_Num` varchar(50) NOT NULL, + `Num` varchar(50), `Model` varchar(50) NOT NULL, - `Current_Location` varchar(50) NOT NULL, - `Status` varchar(50) NOT NULL, - PRIMARY KEY (`Vehicle_ID`) + `Current_Location` varchar(50), + `Status` varchar(50) DEFAULT "IDLE", + PRIMARY KEY (`NUM`) ); CREATE TABLE `Consignor_Consignee` ( @@ -25,25 +24,27 @@ CREATE TABLE `Consignor_Consignee` ( CREATE TABLE `Consignment` ( - `Consignment_ID` varchar(50) NOT NULL, + `ID` varchar(50) NOT NULL, `Consignor_ID` int NOT NULL, `Consignee_ID` int NOT NULL, - `Vehicle_ID` int NOT NULL, - `Loading_Date` date NOT NULL, + `Vehicle_Num` varchar(10) DEFAULT NULL, + `Loading_Date` date DEFAULT NULL, `To` varchar(50) NOT NULL, `From` varchar(50) NOT NULL, `Weight` float NOT NULL, `Rate` float default NULL, `Misc_Charges` float default NULL, `Amount` float default NULL, - `Chargeable_Qty` int default NULL, + `Chargeable_Qty` float default NULL, `Invoice_No.` int NOT NULL, `Invoice_Date` date NOT NULL, + `Invoice_Qty` float NOT NULL, + `Bill_Num` varchar(20) DEFAULT NULL, FOREIGN KEY (`Consignor_ID`) references `Consignor_Consignee`(`ID`), FOREIGN KEY (`Consignee_ID`) REFERENCES `Consignor_Consignee`(`ID`), - FOREIGN KEY (`Vehicle_ID`) REFERENCES `Vehicle`(`Vehicle_ID`), - PRIMARY KEY (`Consignment_ID`) + FOREIGN KEY (`Vehicle_NUM`) REFERENCES `Vehicle`(`NUM`), + PRIMARY KEY (`ID`) ); CREATE TABLE `Repair_Log` ( @@ -54,4 +55,12 @@ CREATE TABLE `Repair_Log` ( `From` varchar(50) NOT NULL, FOREIGN KEY (`Vehicle_ID`) REFERENCES `Vehicle`(`Vehicle_ID`), PRIMARY KEY (`Repair_ID`) -); \ No newline at end of file +); + +CREATE TABLE `Bills` ( + `Num` varchar(20), + `Consignments` int NOT NULL, + `BIll_Date` date NOT NULL, + `Amount` varchar(50) NOT NULL, + PRIMARY KEY (`Num`) +) \ No newline at end of file