Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from server import app

if __name__ == '__main__':
app.run(debug=True)
if __name__ == "__main__":
app.run(debug=True)
49 changes: 26 additions & 23 deletions dbsetup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'''
"""
This is mysql development env setup file.
Just run it once.
'''
"""

import os
import getpass
Expand All @@ -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__ = []
__all__ = []
36 changes: 23 additions & 13 deletions schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -5,44 +5,46 @@ 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` (
`ID` int NOT NULL auto_increment,
`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`)
);


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` (
Expand All @@ -53,4 +55,12 @@ CREATE TABLE `Repair_Log` (
`From` varchar(50) NOT NULL,
FOREIGN KEY (`Vehicle_ID`) REFERENCES `Vehicle`(`Vehicle_ID`),
PRIMARY KEY (`Repair_ID`)
);
);

CREATE TABLE `Bills` (
`Num` varchar(20),
`Consignments` int NOT NULL,
`BIll_Date` date NOT NULL,
`Amount` varchar(50) NOT NULL,
PRIMARY KEY (`Num`)
)
35 changes: 18 additions & 17 deletions server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, "/<string:table_name>")

__all__ = [app, api]
__all__ = [app, api]
81 changes: 46 additions & 35 deletions server/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
]