From 351ec4140930e5abd20b0646ea53300edf16251d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ch=C3=A9rifBALDE?= Date: Wed, 13 Apr 2022 15:04:07 +0200 Subject: [PATCH] 13/04/22 - 14h30 --- articles_avis.py | 206 +++++++++++++++++++++++++++++++++++++++++++++++ main.py | 27 +++++++ 2 files changed, 233 insertions(+) create mode 100644 articles_avis.py diff --git a/articles_avis.py b/articles_avis.py new file mode 100644 index 0000000..25e9665 --- /dev/null +++ b/articles_avis.py @@ -0,0 +1,206 @@ +''' + +Cette class gere les avis et articles sur une formation. + +''' +from pymongo import MongoClient +import pymongo +import json +from flask import Flask, request, jsonify +#from flask_mongoengine import MongoEngine +import json +from bson import ObjectId +import re +import numpy as np +import ela_index_bdd_classes as ela_index +import logging +from datetime import datetime +import prj_common as mycommon +import secrets +from pymongo import ReturnDocument +import inspect +import sys, os +import csv +import pandas as pd + + + +class JSONEncoder(json.JSONEncoder): + def default(self, o): + if isinstance(o, ObjectId): + return str(o) + print(self) + print(o) + return json.JSONEncoder.default(self, o) + +CONNECTION_STRING = "mongodb://localhost/cherifdb" +client = MongoClient(CONNECTION_STRING) +dbname = client['cherifdb'] + +''' +La taille maximal d'un champs à retourner. +Au dela de 300 caractère, le système rame +''' +MAX_CARACT = 300 + + + +''' +Recuperation des tous avis et commentaires +''' +def get_all_articles_avis(diction): + try: + + # Dictionnaire des champs utilisables + field_list = ['token', 'user_ip', 'user_country_code', 'user_country_name', 'user_city', + 'user_postal', 'user_latitude', 'user_longitude', 'user_state', 'search_text'] + + incom_keys = diction.keys() + + ''' + # Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés + # Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API + # Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste + # field_list. + ''' + for val in incom_keys: + if str(val).lower() not in str(field_list).lower(): + mycommon.myprint(str(inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé") + return False, " Impossible de recuperer les articles et avis" + + coll_name = dbname['articles_avis'] + + val_tmp = 1 + insertObject = [] + for x in coll_name.find({'valide': '1', 'locked': '0'}, + {"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0, + "valide": 0, "locked": 0, "url_formation": 0, }): + # mycommon.myprint("AVANT ==> "+str(x['description'])) + val = x['qualite'] + if (len(x['qualite']) > MAX_CARACT): + x['qualite'] = val[:MAX_CARACT] + " ..." + + else: + x['qualite'] = val[:MAX_CARACT] + + val = x['avis'] + if (len(x['avis']) > MAX_CARACT): + x['avis'] = val[:MAX_CARACT] + " ..." + + else: + x['avis'] = val[:MAX_CARACT] + + # mycommon.myprint("APRES ==> " + str(x['description'])) + + user = x + user['id'] = str(val_tmp) + insertObject.append(JSONEncoder().encode(user)) + val_tmp = val_tmp + 1 + + #print(" getObject = ", str(insertObject)) + return True, insertObject + + 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 recuperer les articles et avis" + + +''' +Cette API recupere et retourne un articles / avis +''' +def get_articles_avis(diction): + try: + + # Dictionnaire des champs utilisables + field_list = ['token', 'title_formation', 'user_ip', 'user_country_code', 'user_country_name', + 'user_city','user_postal', 'user_latitude', 'user_longitude', 'user_state'] + + incom_keys = diction.keys() + + ''' + # Verification que les champs reçus dans l'API sont bien dans la liste des champs autorisés + # Cela evite le cas ou une entité tierce ajouter les valeurs inconnu dans l'API + # Ici on doit mettre tous les champs possible (obligatoire ou non) de la BDD dans la liste + # field_list. + ''' + for val in incom_keys: + if str(val).lower() not in str(field_list).lower(): + mycommon.myprint(str(inspect.stack()[0][3]) + " Le champ '" + val + "' n'est pas autorisé") + return False, " Impossible de recuperer l'articles/avis" + + ''' + Une fois qu'on a controlé que toutes les clés mise dans l'API sont correcte. etape precedente, + On controle que les champs obligatoires sont presents dans la liste + ''' + field_list_obligatoire = ['token', 'title_formation'] + + for val in field_list_obligatoire: + if val not in diction: + mycommon.myprint( + str(inspect.stack()[0][3]) + " - La valeur '" + val + "' n'est pas presente dans liste ") + return False, " Impossible de recuperer l'articles/avis" + + + # Recuperation des parametres + mydata = {} + if ("user_ip" in diction.keys()): + if diction['user_ip']: + mydata['user_ip'] = diction['user_ip'] + + if ("user_country_code" in diction.keys()): + if diction['user_country_code']: + mydata['user_country_code'] = diction['user_country_code'] + + if ("user_country_name" in diction.keys()): + if diction['user_country_name']: + mydata['user_country_name'] = diction['user_country_name'] + + if ("user_city" in diction.keys()): + if diction['user_city']: + mydata['user_city'] = diction['user_city'] + + if ("user_postal" in diction.keys()): + if diction['user_postal']: + mydata['user_postal'] = diction['user_postal'] + + if ("user_latitude" in diction.keys()): + if diction['user_latitude']: + mydata['user_latitude'] = diction['user_latitude'] + + if ("user_longitude" in diction.keys()): + if diction['user_longitude']: + mydata['user_longitude'] = diction['user_longitude'] + + if ("user_state" in diction.keys()): + if diction['user_state']: + mydata['user_state'] = diction['user_state'] + + my_title_formation = '' + if ("title_formation" in diction.keys()): + if diction['title_formation']: + mydata['title_formation'] = diction['title_formation'] + my_title_formation = diction['title_formation'] + + + print(" My Data =" + str(mydata)) + + coll_name = dbname['articles_avis'] + insertObject = [] + + for x in coll_name.find({'valide': '1', 'locked': '0', 'title_formation':my_title_formation}, + {"_id": 0, "indexed": 0, "indexed_desc": 0, "indexed_obj": 0, "indexed_title": 0, + "valide": 0, "locked": 0, "url_formation": 0, }): + + user = x + insertObject.append(JSONEncoder().encode(user)) + + + print(" getObject = ", str(insertObject)) + return True, insertObject + + + 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 recuperer l'article/avis" \ No newline at end of file diff --git a/main.py b/main.py index b5437b5..2f31fbf 100644 --- a/main.py +++ b/main.py @@ -20,6 +20,7 @@ import time from OpenSSL import SSL from flask import redirect from flask import Flask, render_template, request, redirect, url_for +import articles_avis as aa DEBUG_LEVEL = logging.DEBUG @@ -838,6 +839,32 @@ def partner_login(): return jsonify(status=status, message=retval) +''' +Cette API recuperer tous les articles et avis sur les formations +''' +@app.route('/myclass/api/get_all_articles_avis/', methods=['POST','GET']) +@crossdomain(origin='*') +def get_all_articles_avis(): + # On recupere le corps (payload) de la requete + payload = request.form.to_dict() + print(" ### payload = ",payload) + status, retval = aa.get_all_articles_avis(payload) + return jsonify(status=status, message=retval) + + + +''' +Cette API recupere un article/avis donné +''' +@app.route('/myclass/api/get_articles_avis/', methods=['POST','GET']) +@crossdomain(origin='*') +def get_articles_avis(): + # On recupere le corps (payload) de la requete + payload = request.form.to_dict() + print(" ### payload = ",payload) + status, retval = aa.get_articles_avis(payload) + return jsonify(status=status, message=retval) + if __name__ == '__main__':