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():
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
def db_insert(query: dict):
if(query is not None):
......@@ -123,6 +136,7 @@ def db_insert(query: dict):
query['id'] = str(random.getrandbits(64))
try:
values = query.values()
print("values received :", values)
cols = query.keys()
sql_new_job_row = "INSERT INTO jobs (%s) VALUES ('%s');" % (", ".join(cols), "','".join(values))
mycursor = database.cursor(buffered=True)
......
# authors: Julien DAVID & Ismail MOUMNI
import socket
import json
import datetime
import os
import sys
import database.database as db
sys.path.append(os.path.realpath('../softwares/'))
import database as db
__RDOS_Dict__ = {}
__RDOS_Dict__ = {"parameters": "request"}
# tools List
__RDOS_Tool__ = {}
__RDOS_Tool__ = db.list_generator()
class RdosServer:
......@@ -18,27 +19,49 @@ class RdosServer:
# Function input address : SERVER IP ADRESS & Port server Port
# Function output query send from client to server
def server_conn(address, PORT):
__RDOS_Tool__ = db.list_generator()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
serv.bind((address, PORT))
# Listening to 5 CLients
serv.listen(5)
# accepting the connection from client and getting client IP
conn, addr = serv.accept()
while True:
if conn:
print('Connexion acceptee depuis l IP : ', addr)
# Receiving Data from Client
data = conn.recv(4096)
query = (json.loads(data.decode('utf-8')))
print("Requete reçu : ", query)
if(query is not None):
# Sending GENERATORS
if (query_valid(query)):
response = db.db_generators()
conn.send(bytes(json.dumps(response), "utf-8"))
# Inserting in DATABASE
else:
db_insert(conn, check_and_complete_parameters(query))
while 1:
# accepting the connection from client and getting client IP
conn, addr = serv.accept()
if conn:
print('Connexion acceptee depuis l IP : ', addr)
# Receiving Data from Client
data = conn.recv(4096)
query = (json.loads(data.decode('utf-8')))
print("Requete reçu : ", query)
#query = json_to_dict(req)
if(query is not None):
# Sending GENERATORS
print(query)
if (match_query_dict(query, __RDOS_Dict__)):
response = db.get_generators()
conn.send(bytes(json.dumps(response), "utf-8"))
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
......@@ -46,12 +69,13 @@ class RdosServer:
# Function input dictionary from client
# Function output boolean true if match else False
def query_valid(data: dict):
if data is not None:
if 'parameters' in data:
if (data['parameters'] != '') & (len(data) <= 2):
return True
else:
return False
if data != {}:
print("heyhey", data)
print(data[parameters])
if (data["parameters"] == 'response'):
return True
else:
return False
else:
raise Exception("Dictionnaire Vide!!")
......@@ -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 input takes a dictionary
# 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:
tool = data.keys().strip('[]')
s = db.getParameters(data['tool'])
tool = list(data.keys())[0]
s = db.getParameters({tool})
parameter = {}
query = {}
if s is not None:
gen = s[0]
gen_default = s[1]
parameter = gen_default
query = data.get(tool)
if match_query_dict(gen.get(tool), query):
for a in query:
if query[a] == "":
print(query[a])
query[a] = parameter.get(a)
return query
parameter = s[1]
q = data.get(tool)
if match_query_dict(parameter.get(tool), q):
check_and_replace(data.get(tool), parameter.get(tool))
return data
else:
raise Exception("Query Doesn't match")
else:
......@@ -129,6 +149,17 @@ def check_and_complete_parameters(data: dict):
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 takes a dictionary request from client side
# Function returns all database generators or raises an error if request doesn't match
......@@ -147,9 +178,9 @@ def db_generators(req: dict):
# 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_insert(s: socket, req: dict):
def db_server_insert(s: socket, req: dict):
if(req is not None):
ins = db.insert_query(req)
ins = db.db_insert(req)
s.send(bytes(json.dumps(ins), "utf-8"))
print("Query send")
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