Commit 05cdbdc7 authored by Ismail Moumni's avatar Ismail Moumni
Browse files

adding Function insert to database

parent 7bb58f5f
Pipeline #1304 failed with stage
in 13 seconds
...@@ -115,6 +115,19 @@ def get_generators(): ...@@ -115,6 +115,19 @@ def get_generators():
generators[result[0]] = [result] generators[result[0]] = [result]
def list_generator():
database = database_connection()
generators = {}
sql_get_generators = "SELECT id, tool from generators"
mycur = database.cursor(buffered=False)
mycur.execute(sql_get_generators)
res = mycur.fetchall()
mycur.close()
for a, b in res:
generators[b] = a
return generators
# Insert in database query send from client and returns insert status # Insert in database query send from client and returns insert status
def db_insert(query: dict): def db_insert(query: dict):
if(query is not None): if(query is not None):
...@@ -123,6 +136,7 @@ def db_insert(query: dict): ...@@ -123,6 +136,7 @@ def db_insert(query: dict):
query['id'] = str(random.getrandbits(64)) query['id'] = str(random.getrandbits(64))
try: try:
values = query.values() values = query.values()
print("values received :", values)
cols = query.keys() cols = query.keys()
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)
......
# authors: Julien DAVID & Ismail MOUMNI # authors: Julien DAVID & Ismail MOUMNI
import socket import socket
import json import json
import datetime
import os import os
import sys import sys
import database.database as db
sys.path.append(os.path.realpath('../softwares/')) sys.path.append(os.path.realpath('../softwares/'))
import database as db
__RDOS_Dict__ = {} __RDOS_Dict__ = {"parameters": "request"}
# tools List # tools List
__RDOS_Tool__ = {} __RDOS_Tool__ = db.list_generator()
class RdosServer: class RdosServer:
...@@ -18,27 +19,49 @@ class RdosServer: ...@@ -18,27 +19,49 @@ class RdosServer:
# Function input address : SERVER IP ADRESS & Port server Port # Function input address : SERVER IP ADRESS & Port server Port
# Function output query send from client to server # Function output query send from client to server
def server_conn(address, PORT): def server_conn(address, PORT):
__RDOS_Tool__ = db.list_generator()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
serv.bind((address, PORT)) serv.bind((address, PORT))
# Listening to 5 CLients # Listening to 5 CLients
serv.listen(5) serv.listen(5)
# accepting the connection from client and getting client IP while 1:
conn, addr = serv.accept() # accepting the connection from client and getting client IP
while True: conn, addr = serv.accept()
if conn: if conn:
print('Connexion acceptee depuis l IP : ', addr) print('Connexion acceptee depuis l IP : ', addr)
# Receiving Data from Client # Receiving Data from Client
data = conn.recv(4096) data = conn.recv(4096)
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): #query = json_to_dict(req)
# Sending GENERATORS if(query is not None):
if (query_valid(query)): # Sending GENERATORS
response = db.db_generators() print(query)
conn.send(bytes(json.dumps(response), "utf-8")) if (match_query_dict(query, __RDOS_Dict__)):
# Inserting in DATABASE response = db.get_generators()
else: conn.send(bytes(json.dumps(response), "utf-8"))
db_insert(conn, check_and_complete_parameters(query)) print("database generators ", response)
conn.close()
# Inserting client query in DATABASE
else:
print("check", check_and_complete_parameters(query))
db_server_insert(conn, query_client(addr, check_and_complete_parameters(query)))
print("query received : ", query)
conn.send(bytes(json.dumps("{'etat':'inserted'}"), "utf-8"))
conn.close()
def query_client(addr, data):
sa = __RDOS_Tool__.get(list(data.keys())[0])
lm = list((data.values()))
s = {"id": "", "idGenerator": "", "IP": "", "timeSubmitted": "", "timeExecuted": "", "timeFinished": "", "status": "", "parametersJSON": "", "directory": "", "url": "", "message": "", "email": ""}
s["id"] = str(os.getuid())
s["idGenerator"] = str(sa)
s["IP"] = str(addr[0])
s["timeSubmitted"] = (str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
s["parametersJSON"] = json.dumps(lm[0])
print(s)
return s
# Function query_valwid matches the query send from client side # Function query_valwid matches the query send from client side
...@@ -46,12 +69,13 @@ class RdosServer: ...@@ -46,12 +69,13 @@ class RdosServer:
# Function input dictionary from client # Function input dictionary from client
# Function output boolean true if match else False # Function output boolean true if match else False
def query_valid(data: dict): def query_valid(data: dict):
if data is not None: if data != {}:
if 'parameters' in data: print("heyhey", data)
if (data['parameters'] != '') & (len(data) <= 2): print(data[parameters])
return True if (data["parameters"] == 'response'):
else: return True
return False else:
return False
else: else:
raise Exception("Dictionnaire Vide!!") raise Exception("Dictionnaire Vide!!")
...@@ -104,23 +128,19 @@ def match_query_dict(biblio: dict, data: dict): ...@@ -104,23 +128,19 @@ def match_query_dict(biblio: dict, data: dict):
# 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
# Function input takes a dictionary # Function input takes a dictionary
# Function output returns query if it matches with database query keys if not it raises an error # Function output returns query if it matches with database query keys if not it raises an error
def check_and_complete_parameters(data: dict): def check_and_complete_parameters(data):
if data is not None: if data is not None:
tool = data.keys().strip('[]') tool = list(data.keys())[0]
s = db.getParameters(data['tool']) s = db.getParameters({tool})
parameter = {} parameter = {}
query = {} query = {}
if s is not None: if s is not None:
gen = s[0] gen = s[0]
gen_default = s[1] parameter = s[1]
parameter = gen_default q = data.get(tool)
query = data.get(tool) if match_query_dict(parameter.get(tool), q):
if match_query_dict(gen.get(tool), query): check_and_replace(data.get(tool), parameter.get(tool))
for a in query: return data
if query[a] == "":
print(query[a])
query[a] = parameter.get(a)
return query
else: else:
raise Exception("Query Doesn't match") raise Exception("Query Doesn't match")
else: else:
...@@ -129,6 +149,17 @@ def check_and_complete_parameters(data: dict): ...@@ -129,6 +149,17 @@ def check_and_complete_parameters(data: dict):
raise Exception("Dictionnaire Vide!!") raise Exception("Dictionnaire Vide!!")
# Function check_and_replace checks query with that and replaces the empty values
# Function input takes 2 dictionaries
# Function output returns matched query
def check_and_replace(query, data):
if query is not None and data is not None:
for a, b in query.items():
if b == '':
query[a] = data.get(a)
return query
# Function db_generators returns database generators # Function db_generators returns database generators
# Function takes a dictionary request from client side # Function takes a dictionary request from client side
# Function returns all database generators or raises an error if request doesn't match # Function returns all database generators or raises an error if request doesn't match
...@@ -147,9 +178,9 @@ def db_generators(req: dict): ...@@ -147,9 +178,9 @@ def db_generators(req: dict):
# Function db_insert send a query to insert in database by socket # 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 takes a socket and dictionary for input
# Function db_insert returns a string if query send # Function db_insert returns a string if query send
def db_insert(s: socket, req: dict): def db_server_insert(s: socket, req: dict):
if(req is not None): if(req is not None):
ins = db.insert_query(req) ins = db.db_insert(req)
s.send(bytes(json.dumps(ins), "utf-8")) s.send(bytes(json.dumps(ins), "utf-8"))
print("Query send") print("Query send")
else: else:
......
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