Ela_Back/tools_cherif/tools_cherif.py

911 lines
37 KiB
Python

import pymongo
import zeep
from pymongo import MongoClient
import json
from bson import ObjectId
import re
from datetime import datetime
import prj_common as mycommon
import secrets
import inspect
import sys, os
import csv
import pandas as pd
from pymongo import ReturnDocument
from math import isnan
import GlobalVariable as MYSY_GV
import ela_index_bdd_classes as eibdd
import email_mgt as email
from validate_email import validate_email
import jinja2
def email_validation():
try:
coll_emails = MYSY_GV.dbname['bdd_email']
cpt = 0
nb_doc = coll_emails.count_documents({'valide':'1', "checked": {"$ne": "1"}})
print(" ### nb_doc = ", nb_doc)
for val in coll_emails.find({'valide':'1', "checked": {"$ne": "1"}}):
cpt = cpt + 1
if ("email_address" in val.keys()):
is_valid = validate_email(
email_address=val['email_address'],
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=10,
check_smtp=True,
smtp_timeout=10,
smtp_helo_host='smtp.office365.com',
smtp_from_address='support@mysy-training.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False)
retval = ""
checked_status = ""
if( is_valid ):
#print(" ### l'adresse ",val['email_address']," est valide ")
retval = True
checked_status = "1"
else:
#print(" ### l'adresse ", val['email_address'], " N'EST PAS valide ")
retval = False
checked_status = "0"
mydata = {}
mytoday = datetime.today().strftime("%d/%m/%Y")
mydata['last_check_date'] = str(mytoday)[0:10]
mydata['checked'] = str("1")
mydata['checked_status'] = str(checked_status)
ret_val = coll_emails.find_one_and_update(
{'email_address': str(val['email_address']), 'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
print(" ### "+str(cpt)+" email traité sur "+str(nb_doc))
return retval, str(cpt)+" adresse email ont été mise à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
def email_validation_mairies():
try:
coll_emails = MYSY_GV.dbname['collect_list_mairies']
cpt = 0
nb_doc = coll_emails.count_documents({'valide': '1', "email_checked": {"$ne": "1"}})
print(" ### nb_doc = ", nb_doc)
for val in coll_emails.find({'valide': '1', "checked": {"$ne": "1"}}):
cpt = cpt + 1
if ("email" in val.keys()):
is_valid = validate_email(
email_address=str(val['email']).strip(),
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=10,
check_smtp=True,
smtp_timeout=10,
smtp_helo_host='smtp.office365.com',
smtp_from_address='support@mysy-training.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False)
retval = ""
checked_status = ""
if (is_valid):
# print(" ### l'adresse ",val['email_address']," est valide ")
retval = True
checked_status = "1"
else:
# print(" ### l'adresse ", val['email_address'], " N'EST PAS valide ")
retval = False
checked_status = "0"
mydata = {}
mytoday = datetime.today().strftime("%d/%m/%Y")
mydata['last_check_date'] = str(mytoday)[0:10]
mydata['email_checked'] = str("1")
mydata['email_checked_status'] = str(checked_status)
ret_val = coll_emails.find_one_and_update(
{'email': str(val['email']), 'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
print(" ### " + str(cpt) + " / " + str(nb_doc))
return retval, str(cpt) + " adresse email ont été mise à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
def email_validation_hopitaux_ehpad():
try:
coll_emails = MYSY_GV.dbname['collect_list_hopitaux_ehpad']
cpt = 0
nb_doc = coll_emails.count_documents({'valide': '1', "email_checked": {"$ne": "1"}})
print(" ### nb_doc = ", nb_doc)
for val in coll_emails.find({'valide': '1', "checked": {"$ne": "1"}}):
cpt = cpt + 1
if ("email" in val.keys()):
is_valid = validate_email(
email_address=str(val['email']).strip(),
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=10,
check_smtp=True,
smtp_timeout=10,
smtp_helo_host='smtp.office365.com',
smtp_from_address='support@mysy-training.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False)
retval = ""
checked_status = ""
if (is_valid):
# print(" ### l'adresse ",val['email_address']," est valide ")
retval = True
checked_status = "1"
else:
# print(" ### l'adresse ", val['email_address'], " N'EST PAS valide ")
retval = False
checked_status = "0"
mydata = {}
mytoday = datetime.today().strftime("%d/%m/%Y")
mydata['last_check_date'] = str(mytoday)[0:10]
mydata['email_checked'] = str("1")
mydata['email_checked_status'] = str(checked_status)
ret_val = coll_emails.find_one_and_update(
{'email': str(val['email']), 'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
print(" ### " + str(cpt) + " / " + str(nb_doc))
return retval, str(cpt) + " adresse email ont été mise à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
def email_validation_list_pos_bio():
try:
coll_emails = MYSY_GV.dbname['collect_list_pos_bio']
cpt = 0
nb_doc = coll_emails.count_documents({'valide': '1', "email_checked": {"$ne": "1"}})
print(" ### nb_doc = ", nb_doc)
for val in coll_emails.find({'valide': '1', "checked": {"$ne": "1"}}):
cpt = cpt + 1
if ("email" in val.keys()):
is_valid = validate_email(
email_address=str(val['email']).strip(),
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=10,
check_smtp=True,
smtp_timeout=10,
smtp_helo_host='smtp.office365.com',
smtp_from_address='support@mysy-training.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False)
retval = ""
checked_status = ""
if (is_valid):
# print(" ### l'adresse ",val['email_address']," est valide ")
retval = True
checked_status = "1"
else:
# print(" ### l'adresse ", val['email_address'], " N'EST PAS valide ")
retval = False
checked_status = "0"
mydata = {}
mytoday = datetime.today().strftime("%d/%m/%Y")
mydata['last_check_date'] = str(mytoday)[0:10]
mydata['email_checked'] = str("1")
mydata['email_checked_status'] = str(checked_status)
ret_val = coll_emails.find_one_and_update(
{'email': str(val['email']), 'valide': '1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER
)
print(" ### " + str(cpt) + " / " + str(nb_doc))
return retval, str(cpt) + " adresse email ont été mise à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la formation"
import socket
import smtplib
import re
import dns.resolver
def test_tab_mail(tab_mail):
try:
email_address = 'emildqsdssdqdsdie.dacossqqazta@3ds.com'
# Step 1: Check email
# Check using Regex that an email meets minimum requirements, throw an error if not
addressToVerify = email_address
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', addressToVerify)
if match == None:
print('Bad Syntax in ' + addressToVerify)
raise ValueError('Bad Syntax')
# Step 2: Getting MX record
# Pull domain name from email address
domain_name = email_address.split('@')[1]
# get the MX record for the domain
my_resolver = dns.resolver.Resolver()
records = my_resolver.resolve(domain_name, 'MX')
mxRecord = records[0].exchange
mxRecord = str(mxRecord)
print(mxRecord)
# Step 3: ping email server
# check if the email address exists
# Get local server hostname
host = socket.gethostname()
# SMTP lib setup (use debug level for full output)
server = smtplib.SMTP()
server.set_debuglevel(0)
# SMTP Conversation
server.connect(mxRecord)
server.helo(host)
server.mail('cbalde@mysy-training.com')
code, message = server.rcpt(str(addressToVerify))
server.quit()
# Assume 250 as Success
if code == 250:
print('Yes')
return True, "OK"
else:
print('N')
return False, "KO"
return
list_mail = ""
if ("list_mail" in tab_mail.keys()):
list_mail = str(tab_mail['list_mail'])
cpt = 0
val = list_mail
print(" list_mail = ", list_mail)
is_valid = validate_email(
email_address=str(val),
check_format=True,
check_blacklist=True,
check_dns=True,
dns_timeout=100,
check_smtp=True,
smtp_timeout=100,
smtp_helo_host='smtp.office365.com',
smtp_from_address='support@mysy-training.com',
smtp_skip_tls=False,
smtp_tls_context=None,
smtp_debug=False)
retval = ""
checked_status = ""
if (is_valid):
print(" ### l'adresse ",val," est valide ")
retval = True
else:
print(" ### l'adresse ", val, " N'EST PAS valide ")
retval = False
return retval, str(cpt) + " adresse email ont été mise à jour "
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de tester le mail"
''' dirty function '''
def dirty():
try:
tab = ['a.maisonneuve@ch-montlucon.fr',
'a.notteghem@ch-stquentin.fr',
'adamasambou@live.fr',
'as.aubert@ch-cannes.fr',
'bduquai@gmail.com',
'berdaguerd@gmail.com',
'bnoetinger@yahoo.fr',
'boucherie.gervais@gmail.com',
'boucherie.laiguillon.lh@gmail.com',
'boucherie.piquenot@gmail.com',
'boucheriebeauvais@gmail.com',
'boucheriefouache@gmail.com',
'boucheriesaintvivien@gmail.com',
'breantbaba@gmail.com',
'c.hugues@ch-stquentin.fr',
'canals.cedric@orange.fr',
'caterinallende@yahoo.es',
'catherine.hardy@ch-ariege-couserans.fr',
'cathysalva@live.fr',
'celine.viteau@ch-soissons.fr',
'charcuterieleger@orange.fr',
'charles@closdesvinsdamour.fr',
'chateaunadalhainaut@gmail.com',
'clotdelorigine@gmail.com',
'contact@bioteafull.fr',
'contact@domainepouderoux.fr',
'contact@herboristerie-moderne.fr',
'contact@lesjardinsdemeraude.fr',
'contact@masbecha.com',
'contact@masdenfelix.com ',
'contact@vins-face-b.fr',
'cyril.marais@ch-soissons.fr',
'cyrilfhal@gmail.com',
'daniel.leclerc@gmail.com',
'direction.ehpad.aixeo@hotmail.fr',
'direction.ehpad.rpc@gmail.com',
'direction@ch-hirson.fr',
'direction@chsi-ainay.fr',
'direction@hi-bsav.fr',
'directiongenerale@ch-stquentin.fr',
'dom.ponsgralet@wanadoo.fr',
'domaine.laguerre@orange.fr',
'domainespiaggia@yahoo.com',
'domitienne@outlook.com',
'drh@cas-forcalquier.fr',
'ducrocq.quentin29@gmail.com',
'ehpad.grdbosquet.villerscotterets@wanadoo.fr',
'ehpad@beauregard-residence.fr',
'enidnamag@hotmail.com',
'eric.heyrman@ch-soissons.fr',
'eric.robart@orange.fr',
'etoiledelabergere486@gmail.com',
'f.mezrouh@ch-stquentin.fr',
'flo.moussellous@gmail.com',
'foyer.occ@wanadoo.fr',
'francoise.moreau@hopcobour.net',
'gdesnoix@chsi-ainay.fr',
'helie.boucherie@orange.fr',
'herve.bessiere@gmail.com',
'hopital.saintmaur@gmail.com',
'info.domainegardies@gmail.com',
'info@masllossanes.fr',
'inge.meierhofer@yahoo.fr',
'j.louisy@ch-stquentin.fr',
'jeanmarie.colin@ch-valvert.fr',
'jfdeu@hotmail.com',
'jp.fardeau@cas-forcalquier.fr',
'labergeriedesabeilles@gmail.com',
'lafermedubiosillon@gmail.com',
'lamerblanche66@gmail.com',
'laurent.lemoux@ch-ghsa.fr',
'laurie@lejardinbiodelaurie.fr ',
'lechantdelaterre66@gmail.com',
'lemasaintantoine@gmail.com',
'lepetitsoleilbio66@outlook.fr',
'les.salicaires.vigneron@gmail.com',
'letempsbio@gmail.com',
'lherberie@protonmail.com',
'ljdt66@gmail.com',
'm.saf@ch-guise.fr',
'marc.veuillet@cgd13.fr',
'masdumoutonnoir@gmail.com',
'maugerdominique@hotmail.com',
'mylene.verdu@gmail.com ',
'n.estin@ch-stquentin.fr',
'naliane@chsi-ainay.fr',
'o.ponties@ch-rodez.fr',
'pierre.espejo2@gmail.com',
'pouletbio@live.fr',
'responsable.rh-log@ehpad-mgasquet.fr',
'romain.cochonbio@yahoo.com',
's.bousmaha@ch-stquentin.fr',
's.junker@ch-montlucon.fr',
'sarlavice76@gmail.com',
'sarlmaisoncuvier@gmail.com',
'scealaroqueta@gmail.com',
'sophie.barbier@ch-ghsa.fr',
'thierry.levionnois@orange.fr',
'veroniquedumont42@gmail.com',
'yanisleroux@orange.fr',
'andre.minyemeck@ehpad-conches.fr',
'anne.quinville@armorsante.bzh',
'audrey.licandro@chu-dijon.fr',
'c.bistue@chuzes.fr',
'ca.doussot@cht-ranceemeraude.fr',
'catherine.lahille@gh-portesdeprovence.fr',
'cecile.chalet@chu-nimes.fr',
'cgreslon@ch-bassindethau.fr',
'christian.soubie@ch-libourne.fr',
'contact-stp@hopitaloleron.net',
'contact@ch-edouard-toulouse.fr',
'contact@hopital-vicfezensac.fr',
'contact@nh-navarre.fr',
'd.faivre@chi-hc.fr',
'david.trouchaud@ght-cdn.fr',
'dg.secretariat@ch-perigueux.fr',
'diandra.tijjini@nh-navarre.fr',
'directeur@ch-saint-renan.fr',
'directeur@hopital-murat.fr',
'direction.generale@ch-perrens.fr',
'direction@ch-claudel.fr',
'direction@ch-condom.com',
'direction@gh-portesdeprovence.fr',
'direction@mr-blamont.fr',
'directionfdcmontpon@orange.fr',
'direhpadsudcher@gmail.com',
'e-barde@chu-montpellier.fr',
'ehpad.gracay@orange.fr',
'ehpad.lebrestalou@wanadoo.fr',
'ehpad.lescedres@outlook.fr',
'florie.bideplan@ch-libourne.fr',
'helene.normand@nh-navarre.fr',
'ifsivierzon@ch-vierzon.fr',
'j-lepage@chu-montpellier.fr',
'jean-baptiste.fleury@armorsante.bzh',
'l.brule@ch-hdn.fr',
'lalliot-bironneau@ch-perrens.fr',
'logistique@hlv.fr',
'logistiqueaudincourt@gmail.com',
'magali.luc@chu-nimes.fr',
'maison-retraite@mr-blamont.fr',
'maisonderetraite.montpon@orange.fr',
'marc.jaffuer@ch-libourne.fr',
'mr.la.guerche@wanadoo.fr',
'mrlaignes@wanadoo.fr',
'p.perrot@ch-stmalo.fr',
'personnel@epms-orbec.fr',
'philippe.charre@gh-portesdeprovence.fr',
'ronan.sanquer@chu-brest.fr',
'sdeduit@ch-vierzon.fr',
'sylvie.briend@ch-dinan.fr',
't-veleine@chu-montpellier.fr',
'tyandudcoz@orange.fr']
coll_bio = MYSY_GV.dbname['collect_list_pos_bio']
coll_ehpad = MYSY_GV.dbname['collect_list_hopitaux_ehpad']
coll_boucherie = MYSY_GV.dbname['collect_list_boucherie']
for val in tab :
for ret1 in coll_bio.find({'email':val}):
if ("email" in ret1.keys()):
print( "'Point de vente BIO', '",ret1['email'], "' => '",ret1['raison_sociale'], "' => '", ret1['adress'], "'=> '", ret1['tel']+"'")
for ret2 in coll_ehpad.find({'email':val}):
if ("email" in ret2.keys()):
print( "'EHPAD & HOPITAUX', '",ret2['email'], "'=> '",ret2['raison_sociale'], "' => '", ret2['adresse'], "'=>' ", ret2['tel']+"'")
for ret3 in coll_boucherie.find({'email':val}):
if ("email" in ret3.keys()):
print("'BOUCHERIE', '", ret3['email'], "'=> '",ret3['raison_sociale'], "' => '---' => '", ret3['tel']+"'")
return True, "ok"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de tester le mail"
# Root de chamilo
url_root = 'https://online.educetera.org/'
# Conexión
from zeep import Client
#server = SOAPProxy(url_root+'/main/webservices/soap.php' )
import requests
import urllib.request
import hashlib
"""
url = "https://lms.mysy-training.com/main/webservices/soap.php"
querystring = {"wsdl":""}
payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n <soap:Header>\n <UserCredentials xmlns=\"http://microsoft.com/webservices/\">\n <userName>---</userName>\n <password>---</password>\n </UserCredentials>\n </soap:Header>\n <soap:Body>\n <getTrainScheduleJSON xmlns=\"http://microsoft.com/webservices/\">\n <station>NY</station>\n </getTrainScheduleJSON>\n </soap:Body>\n</soap:Envelope>"
headers = {
'content-type': "text/xml; charset=utf-8",
'soapaction': 'https://lms.mysy-training.com/main/webservices/soap.php/WSUser.DisableUser'
}
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
print(response.text)
"""
def mysysoap_old():
try:
url = "https://lms.mysy-training.com/main/webservices/soap.php"
querystring = {"wsdl": ""}
url_root = "http://lms.mysy-training.com/"
ewurl = "https://lms.mysy-training.com/main/webservices/soap.php"
full_url = "https://lms.mysy-training.com/main/webservices/testip.php"
url = "https://lms.mysy-training.com/main/webservices/soap.php/WS.test"
security_key = 'da6e9548ebb7137b97913ae7589c85c5' # Se encuentra en el archivo main/inc/conf/configuration.php línea 115
my_ip = requests.get(full_url).text #
print(" my is = ", my_ip) # "'#readlines()[0][:-1]
secret_key = hashlib.sha1(str(my_ip + security_key).encode('utf-8')).hexdigest()
print(" secret_key = ", secret_key) # "'#readlines()[0][:-1]
url = 'http://www.dneonline.com/calculator.asmx'
xml = """
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/">
<soap:Header/>
<soap:Body>
<tem:Add>
<tem:intA>50</tem:intA>
<tem:intB>20</tem:intB>
</tem:Add>
</soap:Body>
</soap:Envelope>"""
headers = {'content-type': 'application/soap+xml; charset=utf-8'}
#r1 = requests.post(url, data=xml, headers=headers)
url = 'https://lms.mysy-training.com/main/webservices/soap.php'
xml = """
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/">
<soap:Header/>
<soap:Body>
<tem:WS.test>
</tem:WS.test>
</soap:Body>
</soap:Envelope>"""
headers = {'content-type': 'application/soap+xml; charset=utf-8'}
r1 = requests.post(url, data=xml, headers=headers)
print(r1.text)
return True, "ok"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de tester le mail"
from zeep import Client, Settings
def mysysoap():
try:
"""wsdl = "http://www.dneonline.com/calculator.asmx?WSDL"
client = Client(wsdl)
val = client.service.Add(3, 5)
print(val)
"""
security_key = 'da6e9548ebb7137b97913ae7589c85c5' # Se encuentra en el archivo main/inc/conf/configuration.php línea 115
full_url = "https://lms.mysy-training.com/main/webservices/testip.php"
my_ip = requests.get(full_url).text #
print(" my is = ", my_ip) # "'#readlines()[0][:-1]
secret_key = hashlib.sha1(str(my_ip + security_key).encode('utf-8')).hexdigest()
print(" secret_key = ", secret_key) # "'#readlines()[0][:-1]
url = "http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
url="https://lms.mysy-training.com/main/webservices/soap.php?wsdl"
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="https://lms.mysy-training.com/main/webservices/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body>
<ns0:WSCreateUsers>
<secret_key>135b6ca3b7ed29fa787ff011859fd76ec5e1b51c</secret_key>
<users>['1504']</users>
</ns0:WSCreateUsers>
</ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url, data=body, headers=headers)
print(response.content)
val = "grr"
return True, "ok val = "+str(response.content)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de tester le mail"
# Connexion mariadb sur serveur
import mariadb
import hashlib
import bcrypt
def mysylmsdb():
try:
# Rcuperation de la sequence de l'objet "lms_user_id" dans la collection : "mysy_sequence"
retval = MYSY_GV.dbname['mysy_sequence'].find_one({'related_mysy_object':'lms_user_id', 'valide':'1'})
print(" ### retval = ",retval)
mypasswd = 'sekou'.encode('UTF-8')
salt = bcrypt.gensalt()
hashed_pwd = bcrypt.hashpw(mypasswd, salt)
salt = salt.encode('UTF-8')
hashed_pwd = hashed_pwd.encode('UTF-8')
print(" ## HASHED hashed = ", str(hashed_pwd), " SALT = , ", str(salt))
if (retval is None or "current_val" not in retval.keys()):
mycommon.myprint(" Impossible de récupérer la sequence 'mysy_sequence' ")
return False, "Impossible de récupérer la sequence 'mysy_sequence'"
new_lms_user_id = str(retval['prefixe'])+str(retval['current_val'])
local_status, local_val = mycommon.IsInt(new_lms_user_id)
if( local_status is False):
mycommon.myprint(" Impossible de generer l'ID du user LMS. La valeur actuelle est ", new_lms_user_id)
return False, " Impossible de generer l'ID du user LMS"
current_seq_value = str(retval['current_val'])
conn = mariadb.connect(
user=MYSY_GV.MYSY_MARIADB_USER,
password=MYSY_GV.MYSY_MARIADB_USER_PASS,
host=MYSY_GV.MYSY_MARIADB_HOST,
port=MYSY_GV.MYSY_MARIADB_PORT,
database=MYSY_GV.MYSY_LMS_BDD
)
cur = conn.cursor()
# retrieving information
cur.execute("SELECT username, email_canonical FROM user WHERE id=?", (2,))
for username, email_canonical in cur:
print(f"username: {username}, email_canonical : {email_canonical}")
# insert information
my_query = "INSERT INTO user SET id='"+str(new_lms_user_id)+"' , " \
"user_id='"+str(new_lms_user_id)+"' , " \
"lastname = 'carter', " \
"firstname = 'vince_022', " \
"username = 'username_1022', " \
"salt = '"+str(salt)+"'," \
" registration_date = '2022-04-17 15:34:43'," \
" credentials_expired='0', " \
"enabled='1', " \
"expired='0', " \
" status = '1', " \
"password = '"+str(hashed_pwd)+"', " \
"locked = '0', " \
"username_canonical = 'username_1022', " \
" email_canonical = 'username@mano2.fr', " \
"email = 'username@mano2.fr'," \
" official_code = 'AAA', " \
"creator_id = '1', " \
"auth_source = 'platform'," \
"roles = 'a:0:{}', " \
"language = 'french'," \
"active = '1';"
try:
#cur.execute("INSERT INTO employees (first_name,last_name) VALUES (?, ?)", ("Maria", "DB"))
cur.execute(my_query)
except mariadb.Error as e:
print(f"Error: {e}")
mycommon.myprint(" Impossible de créer l'utilisateur LMS "+str({e}))
return False, "Impossible de créer l'utilisateur LMS "+str({e})
conn.commit()
print(f"Last Inserted ID: {cur.lastrowid}")
conn.close()
# Crementation de la sequence de l'objet "lms_user_id" dans la collection : "mysy_sequence"
new_sequence_value = int(current_seq_value)+1
mydata = {'current_val':new_sequence_value}
ret_val2 = MYSY_GV.dbname['mysy_sequence'].find_one_and_update({'related_mysy_object':'lms_user_id', 'valide':'1'},
{"$set": mydata},
return_document=ReturnDocument.AFTER,
upsert= False,
)
return True, "Connexion mariadb OKK"
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, " Connexion mariadb KOOO"
def test_web_service(diction):
try:
if( diction ):
print(" ### diction dans la fonction = ", diction)
else:
print(" ### diction dans la fonction est vide")
return True, "Test WebService OK Diction = "+str(diction)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, "Test WebService KOOO"
def test_web_service2(diction):
try:
print(" #### ENVIRONNEMENT = "+str(MYSY_GV.MYSY_ENV)+" ")
if( diction ):
print(" ### diction dans la fonction = ", diction)
else:
print(" ### diction dans la fonction est vide")
return True, "ENV = "+str(MYSY_GV.MYSY_ENV)+" Test WebService OK Diction = "+str(diction)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, "Test WebService KOOO"
"""
Cette fonction permet de tester l'utilisation de jinja2 avec
des informations stockées dans une base de données
"""
def test_jnja2_database(diction):
try:
# Recuperation des information du template
Document_Template_Data = MYSY_GV.dbname['courrier_template'].find_one({'ref_interne':'test01'})
if( Document_Template_Data is None):
mycommon.myprint(str(inspect.stack()[0][3]) + " - Aucun template avec 'ref_interne':'test01' ")
#return False, " - Aucun template avec 'ref_interne':'test01' "
elif( "type_doc" in Document_Template_Data.keys()):
print(" ### type_doc = ", str(Document_Template_Data['type_doc']))
tm = jinja2.Template("My name is {{ per.name }} and I am {{ per.age }}")
person = {'name': 'Cherif BALDE', 'age': 41}
msg = tm.render(per=person)
print(" ### MSG APRES JINJA2 = ",msg )
return True, "test_jnja2_database => OK : MESSAGE = "+str(msg)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
mycommon.myprint(str(inspect.stack()[0][3]) + " -" + str(e) + " - Line : " + str(exc_tb.tb_lineno))
return False, "test_jnja2_database KOOO"
"""
Cette fonction retourne la liste des champs (+ collection) utilisable dans la personnalisation d'un document
"""
def Get_Personnalisable_Collection_Fields():
try:
RetObject = []
mycollection_field1 = {"collection_technical_name":'inscription', "collection_fonctional_name":'Inscription', "field_technical_name":'session_id', "field_fonctional_name":'Session Code'}
mycollection_field2 = {"collection_technical_name":'inscription', "collection_fonctional_name":'Inscription', "field_technical_name": 'class_internal_url', "field_fonctional_name": 'Title Formation'}
mycollection_field3 = {"collection_technical_name":'inscription', "collection_fonctional_name":'Inscription', "field_technical_name": 'date_du', "field_fonctional_name": 'Date debut'}
mycollection_field4 = {"collection_technical_name":'inscription', "collection_fonctional_name":'Inscription', "field_technical_name": 'date_au', "field_fonctional_name": 'Date Fin'}
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field1))
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field2))
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field3))
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field4))
mycollection2_field1 = {"collection_technical_name": 'myclass', "collection_fonctional_name": 'Formation', "field_technical_name": 'title', "field_fonctional_name": 'Titre'}
mycollection2_field2 = {"collection_technical_name": 'myclass', "collection_fonctional_name": 'Formation',"field_technical_name": 'plus_produit', "field_fonctional_name": 'Avantage'}
mycollection2_field3 = {"collection_technical_name": 'myclass', "collection_fonctional_name": 'Formation',"field_technical_name": 'objectif', "field_fonctional_name": 'Objectif'}
RetObject.append(mycommon.JSONEncoder().encode(mycollection2_field1))
RetObject.append(mycommon.JSONEncoder().encode(mycollection2_field2))
RetObject.append(mycommon.JSONEncoder().encode(mycollection2_field3))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la liste collections personnalisables"
"""
Fonction retourne la liste des collection eligibles à la personnalisation des document
"""
def Get_Personnalisable_Collection():
try:
RetObject = []
mycollection_field1 = {"collection_technical_name": 'inscription', "collection_fonctional_name": 'Inscription',}
mycollection_field2 = {"collection_technical_name": 'myclass', "collection_fonctional_name": 'Formation',}
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field1))
RetObject.append(mycommon.JSONEncoder().encode(mycollection_field2))
return True, RetObject
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
print(str(inspect.stack()[0][3]) + " -" + str(e) + " - ERRORRRR AT Line : " + str(exc_tb.tb_lineno))
return False, " Impossible de récupérer la liste collections personnalisables"