Commit 58eced46 authored by Ismail Moumni's avatar Ismail Moumni
Browse files

adding process query Functions

parent 838d8878
Pipeline #1373 failed with stage
in 14 seconds
...@@ -115,7 +115,7 @@ def get_generators(): ...@@ -115,7 +115,7 @@ def get_generators():
generators[result[0]] = [result] generators[result[0]] = [result]
def li_gen(): def list_gen():
database = database_connection() database = database_connection()
generators = {} generators = {}
sql_get_generators = "SELECT id, tool from generators" sql_get_generators = "SELECT id, tool from generators"
...@@ -129,7 +129,7 @@ def li_gen(): ...@@ -129,7 +129,7 @@ def li_gen():
# Insert in database query send from client and returns insert status 1 if inserted # Insert in database query send from client and returns insert status 1 if inserted
def db_new_job(query: dict): def db_insert(query: dict):
if(query is not None): if(query is not None):
database = database_connection() database = database_connection()
if(db_job_check(query) != 0): if(db_job_check(query) != 0):
...@@ -141,15 +141,13 @@ def db_new_job(query: dict): ...@@ -141,15 +141,13 @@ def db_new_job(query: dict):
sql_new_job_row = "INSERT INTO jobs (%s) VALUES ('%s');" % (", ".join(cols), "','".join(values)) sql_new_job_row = "INSERT INTO jobs (%s) VALUES ('%s');" % (", ".join(cols), "','".join(values))
mycursor = database.cursor(buffered=True) mycursor = database.cursor(buffered=True)
mycursor.execute(sql_new_job_row) mycursor.execute(sql_new_job_row)
print("Record inserteds in DB :", query.values)
database.commit() database.commit()
mycursor.close() mycursor.close()
database.close() database.close()
res = db_job_check(query) return (mycursor.rowcount, "Record inserted successfully into job table")
print("res:", res)
return res
except mysql.connector.Error as err: except mysql.connector.Error as err:
print("MYSQL Error :{}".format(err)) return ("MYSQL Error :{}".format(err))
# Checks existance of query ID in database and returns the status # Checks existance of query ID in database and returns the status
......
...@@ -11,7 +11,7 @@ import database as db # noqa E402 ...@@ -11,7 +11,7 @@ import database as db # noqa E402
__RDOS_Dict__ = {"parameters": "request"} __RDOS_Dict__ = {"parameters": "request"}
# tools List # tools List
# __RDOS_Tool__ = db.list_generators() # __RDOS_Tool__ = db.list_gen()
class RdosServer: class RdosServer:
...@@ -24,7 +24,7 @@ class RdosServer: ...@@ -24,7 +24,7 @@ class RdosServer:
serv.bind((address, PORT)) serv.bind((address, PORT))
# Listening to 5 CLients # Listening to 5 CLients
serv.listen(5) serv.listen(5)
while 1: while True:
# accepting the connection from client and getting client IP # accepting the connection from client and getting client IP
conn, addr = serv.accept() conn, addr = serv.accept()
if conn: if conn:
...@@ -34,43 +34,57 @@ class RdosServer: ...@@ -34,43 +34,57 @@ class RdosServer:
query = (json.loads(data.decode('utf-8'))) query = (json.loads(data.decode('utf-8')))
print("Requete reçu : ", query) print("Requete reçu : ", query)
if (query is not None): if (query is not None):
# Sending GENERATORS
print(query) print(query)
if (match_query_dict(query, __RDOS_Dict__)): query_process(conn, query)
response = db.get_generators() conn.close()
conn.send(bytes(json.dumps(response), "utf-8"))
print("database generators ", response)
conn.close() # Function query_process checks query to get generators or to insert query
# Inserting client query in DATABASE # Function takes 2 parameters socket and query (get generator query or to insert in database a new job)
else: # Function returns generators list to client or returns insert result to client
print("check", check_and_complete_parameters(query)) def query_process(sock: socket, query: dict):
res = db_server_insert(conn, query_client(addr, check_and_complete_parameters(query))) # Sending GENERATORS
# print("query : " , query) if (match_query_dict(query, __RDOS_Dict__)):
if (res == 1): response = db.get_generators()
conn.send(bytes(res, "utf-8")) sock.send(bytes(json.dumps(response), "utf-8"))
else: print("database generators ", response)
conn.send(bytes("query not inserted !!", "utf-8")) # Inserting client query in DATABASE
conn.close() else:
print("check", check_and_complete_parameters(query))
res = db_send_job(sock, query_fields(sock, check_and_complete_parameters(query)))
# Function query_client creates an insert query to send to server print(res)
# Function query_fields generates default fields to insert query send from client to database
# Function takes 2 parameters addr : IP address of client and data : Generators values # Function takes 2 parameters addr : IP address of client and data : Generators values
# Function return a valid insert query # Function return a valid insert query
def query_client(addr, data): def query_fields(addr, data):
__RDOS_Tool__ = db.li_gen() __RDOS_Tool__ = db.list_gen()
sa = __RDOS_Tool__.get(list(data.keys())[0]) sa = __RDOS_Tool__.get(list(data.keys())[0])
lm = list((data.values())) lm = list((data.values()))
s = {"id": "", "idGenerator": "", "IP": "", "timeSubmitted": "", "timeExecuted": "", s = {"id": "", "idGenerator": "", "IP": "", "timeSubmitted": "", "timeExecuted": "",
"timeFinished": "", "status": "", "parametersJSON": "", "directory": "", "url": "", "message": "", "email": ""} "timeFinished": "", "status": "", "parametersJSON": "", "directory": "", "url": "", "message": "", "email": ""}
s["id"] = str(os.getuid()) s["id"] = str(os.getuid())
s["idGenerator"] = str(sa) s["idGenerator"] = str(sa)
s["IP"] = str(addr[0]) s["IP"] = addr.getpeername()[0]
s["timeSubmitted"] = (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) s["timeSubmitted"] = (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
s["parametersJSON"] = json.dumps(lm[0]) s["parametersJSON"] = json.dumps(lm[0])
print(s) print(s)
return s return s
# Function db_new_job send a query to insert in database by socket
# Function db_new_job takes a socket and dictionary for input
# Function db_new_job returns a string if query send
def db_send_job(s: socket, req: dict):
if(req is not None):
ins = db.db_new_job(req)
s.send(bytes(json.dumps(ins), "utf-8"))
print("Query send")
else:
raise Exception("Empty Query")
# Function query_valwid matches the query send from client side # Function query_valwid matches the query send from client side
# with the the parameter dict # with the the parameter dict
# Function input dictionary from client # Function input dictionary from client
...@@ -125,7 +139,7 @@ def match_query_dict(biblio: dict, data: dict): ...@@ -125,7 +139,7 @@ def match_query_dict(biblio: dict, data: dict):
if biblio is not None and data is not None: if biblio is not None and data is not None:
return biblio.keys() == data.keys() return biblio.keys() == data.keys()
else: else:
raise ValueError("Error Dict Values ") raise ValueError("Dictionnaire Vide ")
# Function check_and_complete_parameters verifies json send from client to server by matching it with database query # Function check_and_complete_parameters verifies json send from client to server by matching it with database query
...@@ -151,15 +165,17 @@ def check_and_complete_parameters(data): ...@@ -151,15 +165,17 @@ def check_and_complete_parameters(data):
raise Exception("Dictionnaire Vide!!") raise Exception("Dictionnaire Vide!!")
# Function check_and_replace checks query with that and replaces the empty values # Function check_and_replace checks query with default_parameters of generator and replaces empty values with default_parameters from generator
# Function input takes 2 dictionaries # Function input takes 2 dictionaries
# Function output returns matched query # Function output returns matched query
def check_and_replace(query, data): def check_and_replace(query: dict, default_parameters: dict):
if query is not None and data is not None: if query is not None and default_parameters is not None:
for a, b in query.items(): for a, b in query.items():
if b == '': if b == '':
query[a] = data.get(a) query[a] = default_parameters.get(a)
return query return query
else:
raise Exception("Dictionnaire Vide!!")
# Function db_generators returns database generators # Function db_generators returns database generators
...@@ -177,18 +193,6 @@ def db_generators(req: dict): ...@@ -177,18 +193,6 @@ def db_generators(req: dict):
raise Exception("Dictionnaire Vide!!") raise Exception("Dictionnaire Vide!!")
# Function db_insert send a query to insert in database by socket
# Function db_insert takes a socket and dictionary for input
# Function db_insert returns a string if query send
def db_server_insert(s: socket, req: dict):
if(req is not None):
ins = db.db_insert(req)
s.send(bytes(json.dumps(ins), "utf-8"))
print("Query send")
else:
raise Exception("Invalid Query")
if __name__ == '__main__': if __name__ == '__main__':
# TEST FOR Docker # TEST FOR Docker
RdosServer.server_conn('127.0.0.1', '9393') RdosServer.server_conn('127.0.0.1', '9393')
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment