def create_a_student_from_token(): r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if 'token' not in data: return ERRORS.BAD_REQUEST token = data['token'] a: AskCreation = AskCreation.query.filter_by(token=token).one_or_none() if not a: # Token does not exists return ERRORS.RESOURCE_NOT_FOUND etu = create_a_student(data) if type(etu) is not Etudiant: return etu # this is an error AskCreation.query.filter_by(token=token).delete() db_session.commit() return flask.jsonify(etu)
def import_domain_from_file(filename: str): """ Import base file for populating domain table Domain line must be: internal_name display_name """ with open(filename) as fp: i = 0 for line in fp: i += 1 parts: List[str] = line.strip().split('\t') try: domain, name = parts except: print( f"Invalid line {i}: Incorrect number of elements in line.") continue d: Domaine = Domaine.query.filter_by(domaine=domain).all() if len(d): continue d = Domaine.create(domaine=domain, nom=name) db_session.add(d) db_session.commit()
def make_domain(): r = get_request() if not is_teacher(): return ERRORS.INVALID_CREDENTIALS if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'domain', 'name'} <= set(data): return ERRORS.MISSING_PARAMETERS domain, nom = data['domain'], data['name'] ## Search for similar domains f = Domaine.query.filter(Domaine.domaine.ilike(f"{domain}")).all() if len(f): return flask.jsonify(f[0]), 200 # Create new domain dom = Domaine.create(domaine=domain, nom=nom) db_session.add(dom) db_session.commit() return flask.jsonify(dom), 201
def modify_entreprise(): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS r = get_request() if not r.is_json: return ERRORS.INVALID_INPUT_TYPE data = r.json if not {'name', 'town', 'size', 'status', 'id'} <= set(data): return ERRORS.MISSING_PARAMETERS if type(data['id']) is not int: return ERRORS.INVALID_INPUT_TYPE e: Entreprise = Entreprise.query.filter_by( id_entreprise=int(data['id'])).one_or_none() if not e: return ERRORS.COMPANY_NOT_FOUND name, city, size, status = data['name'], data['town'], data[ 'size'], data['status'] if type(name) is not str: return ERRORS.INVALID_INPUT_TYPE special_check = r"^[\w_ -]+$" if not re.match(special_check, name): return ERRORS.INVALID_INPUT_VALUE e.nom = name if city != e.ville: gps_coords = get_location_of_company(city) e.ville = city e.lat = gps_coords[0] e.lng = gps_coords[1] if type(size) is not str: return ERRORS.INVALID_INPUT_TYPE valid_comp_size = {"small", "big", "medium", "very_big"} if size not in valid_comp_size: return ERRORS.UNEXPECTED_INPUT_VALUE e.taille = size if type(status) is not str: return ERRORS.INVALID_INPUT_TYPE valid_comp_status = {"public", "private"} if status not in valid_comp_status: return ERRORS.UNEXPECTED_INPUT_VALUE e.statut = status db_session.commit() return flask.jsonify(e)
def delete_domain(id: int): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS d: Domaine = Domaine.query.filter_by(id_domaine=id).one_or_none() if not d: return "" other_domain: Domaine = Domaine.query.filter_by( domaine="other").one_or_none() domain_id = None if other_domain: domain_id = other_domain.id_domaine if other_domain.id_domaine == id: return ERRORS.BAD_REQUEST Stage.query.filter_by(id_domaine=id).update({"id_domaine": domain_id}) Emploi.query.filter_by(id_domaine=id).update({"id_domaine": domain_id}) db_session.delete(d) db_session.commit() return ""
def make_internship(): r = get_request() stu = get_student_or_none() if not r.is_json: return ERRORS.BAD_REQUEST if not stu: return ERRORS.STUDENT_NOT_FOUND data = r.json if not {'promo_year', 'company', 'domain', 'contact'} <= set(data): return ERRORS.MISSING_PARAMETERS promo_year, id_entreprise, domain, id_contact = data['promo_year'], data['company'], data['domain'], data['contact'] # Check if promo_year is okay for this student ! if stu.annee_sortie: if not int(stu.annee_entree) <= int(data['promo_year']) <= int(stu.annee_sortie): return ERRORS.INVALID_DATE else: if not int(stu.annee_entree) <= int(data['promo_year']): return ERRORS.INVALID_DATE ## Check company id ent: Entreprise = Entreprise.query.filter_by(id_entreprise=id_entreprise).one_or_none() if not ent: return ERRORS.COMPANY_NOT_FOUND ## Domain to id dom: Domaine = Domaine.query.filter_by(domaine=domain).one_or_none() if not dom: return ERRORS.DOMAIN_NOT_FOUND id_domain = dom.id_domaine ## Check contact id if id_contact is not None: cont: Contact = Contact.query.filter_by(id_contact=id_contact).one_or_none() if not cont: return ERRORS.CONTACT_NOT_FOUND # Create new internship stu.refresh_update() inter = Stage.create( promo=promo_year, id_entreprise=int(id_entreprise), id_domaine=id_domain, id_contact=int(id_contact) if id_contact is not None else None, id_etu=stu.id_etu ) db_session.add(inter) db_session.commit() return flask.jsonify(inter), 201
def make_entreprise(): r = get_request() stu = get_student_or_none() if not stu or not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'name', 'city', 'size', 'status'} <= set(data): return ERRORS.MISSING_PARAMETERS name, city, size, status = data['name'], data['city'], data[ 'size'], data['status'] ## Search for similar company f = Entreprise.query.filter( and_(Entreprise.nom.ilike(f"{name}"), Entreprise.ville.ilike(f"{city}"))).all() if len(f): return flask.jsonify(f[0]) if type(name) is not str: return ERRORS.INVALID_INPUT_TYPE special_check = r"^[\w_ -]+$" if not re.match(special_check, name): return ERRORS.INVALID_INPUT_VALUE # Checks for size and status (enum voir TS interfaces.ts) if type(size) is not str: return ERRORS.INVALID_INPUT_TYPE valid_comp_size = {"small", "big", "medium", "very_big"} if size not in valid_comp_size: return ERRORS.UNEXPECTED_INPUT_VALUE # Checks for status (enum voir TS interfaces.ts) if type(status) is not str: return ERRORS.INVALID_INPUT_TYPE valid_comp_status = {"public", "private"} if status not in valid_comp_status: return ERRORS.UNEXPECTED_INPUT_VALUE gps_coords = get_location_of_company(city) # Create new company comp = Entreprise.create(nom=name, ville=city, taille=size, statut=status, lat=gps_coords[0], lng=gps_coords[1]) db_session.add(comp) db_session.commit() return flask.jsonify(comp), 201
def updateRoute(userID, routeId, dict): try: originalRouteGroup = getRoute(userID, {'id':routeId}) for routeGroupParam in dict: setattr(originalRouteGroup, routeGroupParam,dict[routeGroupParam]) db_session.commit() return True except Exception: return False
def addObjectAttributes(userId, groupId, objectAttributes): if ObjectAttributes.query.filter( ObjectAttributes.objectId == groupId).filter( ObjectAttributes.name == objectAttributes.name).first(): print("This attribute already exists!") return if isValidUser(userId) and isValidRouteGroup(groupId): db_session.add(objectAttributes) db_session.commit()
def modify_internship(): r = get_request() stu = get_student_or_none() if not stu or not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not 'internship' in data: return ERRORS.MISSING_PARAMETERS internship: Stage = Stage.query.filter_by(id_stage=data['internship']).one_or_none() if not internship: return ERRORS.RESOURCE_NOT_FOUND if not is_teacher() and internship.id_etu != stu.id_etu: return ERRORS.INVALID_CREDENTIALS if 'promo_year' in data: internship.promo = data['promo_year'] if 'company' in data: ent: Entreprise = Entreprise.query.filter_by(id_entreprise=data['company']).one_or_none() if not ent: db_session.rollback() return ERRORS.COMPANY_NOT_FOUND internship.id_entreprise = ent.id_entreprise if 'domain' in data: dom: Domaine = Domaine.query.filter_by(domaine=data['domain']).one_or_none() if not dom: db_session.rollback() return ERRORS.DOMAIN_NOT_FOUND internship.id_domaine = dom.id_domaine if 'contact' in data: if data['contact'] is None: internship.id_contact = None else: cont: Contact = Contact.query.filter_by(id_contact=data['contact']).one_or_none() if not cont: db_session.rollback() return ERRORS.CONTACT_NOT_FOUND internship.id_contact = cont.id_contact stu.refresh_update() db_session.commit() return flask.jsonify(internship)
def addRoute(userId, routeGroup): if isValidUser(userId): # if isValidRoute(routeGroup.objectName): # print ('in error', routeGroup.objectName) # generalLogger.error("Error: RouteGroup '" + routeGroup.objectName + "' already added to userID '" + str(userId) + "'") # return # print('IN DB', routeGroup) db_session.add(routeGroup) db_session.commit() generalLogger.info("RouteGroup '" + routeGroup.objectName + "' added to userID '" + str(userId) + "'")
def refresh_locations_of_company(): companies: List[Entreprise] = Entreprise.query.filter_by(lat=None).all() for c in companies: print("Fetching company " + str(c.ville)) coords = get_location_of_company(str(c.ville), True) c.lat = coords[0] c.lng = coords[1] db_session.commit()
def updateObjectAttributes(userId, attributeId, attrDict): try: originalObjectAttribute = getSingleObjectAttribute(userId, attributeId) for objectAttributeParam in attrDict: setattr(originalObjectAttribute, objectAttributeParam, attrDict[objectAttributeParam]) db_session.commit() return True except Exception: return False
def create_a_student(data, with_mail=True): # Si toutes ces clés ne sont pas présentes dans le dict if not { 'first_name', 'last_name', 'email', 'year_in', 'entered_in', 'graduated' } <= set(data): return ERRORS.MISSING_PARAMETERS first_name, last_name, email = data['first_name'], data['last_name'], data[ 'email'] year_in, entree, diplome = data['year_in'], data['entered_in'], data[ 'graduated'] student_check = Etudiant.query.filter_by(mail=email).all() if len(student_check): return ERRORS.STUDENT_EXISTS special_check = r"^[\w_ -]+$" if not re.match(special_check, first_name): return ERRORS.INVALID_INPUT_VALUE if not re.match(special_check, last_name): return ERRORS.INVALID_INPUT_VALUE email_catch = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" if not re.match(email_catch, email): return ERRORS.INVALID_EMAIL current_date = datetime.datetime.now().date().year if type(diplome) is not bool: return ERRORS.INVALID_INPUT_TYPE try: if int(year_in) > current_date or int(year_in) < 2015: return ERRORS.INVALID_DATE except: return ERRORS.INVALID_INPUT_TYPE # Create student etu = Etudiant.create(nom=last_name, prenom=first_name, mail=email, annee_entree=year_in, entree_en_m1=entree == "M1", diplome=diplome) db_session.add(etu) db_session.commit() # Create a token automatically and send the welcome e-mail if with_mail: send_welcome_mail(etu.id_etu) return etu
def import_students_from_file(filename: str): """ Import base file for populating students Student line must be: first_name last_name email graduation_year is_graduated(1/0) """ with open(filename) as fp: i = 0 for line in fp: i += 1 if not line.strip(): continue parts: List[str] = line.strip().split('\t') try: first_name, last_name, email, graduation_year, is_in_m1, is_graduated = parts except: print( f"Invalid line {i}: Incorrect number of elements in line.") continue try: year_in = int(graduation_year) - 2 graduation_year = int(graduation_year) if graduation_year < 2015: raise ValueError("Invalid gradutation date") except: print( f"Invalid line {i}: Graduation year is not valid ({graduation_year})." ) continue e: Etudiant = Etudiant.query.filter_by(mail=email).one_or_none() if e: print( f"Line {i}: Student already exists (conflict in e-mail address)" ) continue etu = Etudiant.create(nom=last_name, prenom=first_name, mail=email, annee_entree=year_in, annee_sortie=graduation_year, entree_en_m1=(is_in_m1 == "1"), diplome=(is_graduated == "1")) db_session.add(etu) db_session.commit()
def create_ask_creation_token(mail: str, matches): ## Check if AskCreation already sended AskCreation.query.filter_by(mail=mail).delete() token = generate_random_token() a = AskCreation.create(token, mail) db_session.add(a) db_session.commit() return '<a href="' + SITE_URL + '/profile_create?token=' + str( a.token) + f'" target="_blank">{matches.group(1)}</a>'
def save_viz_response(request): current_user = get_user_from_cookie(request, 'USER_COOKIE') current_user.theme1 = request.form['theme1'] current_user.theme1_word1 = request.form['theme1_word1'] current_user.theme1_word2 = request.form['theme1_word2'] current_user.theme1_word3 = request.form['theme1_word3'] current_user.theme2 = request.form['theme2'] current_user.theme2_word1 = request.form['theme2_word1'] current_user.theme2_word2 = request.form['theme2_word2'] current_user.theme2_word3 = request.form['theme2_word3'] current_user.end_time = str(datetime.datetime.now()) db_session.commit()
def merge_companies(): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'main', 'children'} <= set(data): return ERRORS.MISSING_PARAMETERS main, children = data['main'], data['children'] if type(main) is not int or type(children) is not list: return ERRORS.BAD_REQUEST main_company: Entreprise = Entreprise.query.filter_by( id_entreprise=main).one_or_none() if not main_company: return ERRORS.COMPANY_NOT_FOUND children_companies: List[Entreprise] = [] for c in children: if type(c) is not int: return ERRORS.BAD_REQUEST ent = Entreprise.query.filter_by(id_entreprise=c).one_or_none() if not ent: return ERRORS.COMPANY_NOT_FOUND children_companies.append(ent) # For each job/internship relied to children_companies, set main_company for c in children_companies: Emploi.query.filter_by(id_entreprise=c.id_entreprise).update( {'id_entreprise': main_company.id_entreprise}) Stage.query.filter_by(id_entreprise=c.id_entreprise).update( {'id_entreprise': main_company.id_entreprise}) # Delete every children company for c in children_companies: Contact.query.filter_by(id_entreprise=c.id_entreprise).update( {'id_entreprise': main_company.id_entreprise}) db_session.delete(c) db_session.commit() return ""
def merge_domains(): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'main', 'children'} <= set(data): return ERRORS.MISSING_PARAMETERS main, children = data['main'], data['children'] if type(main) is not int or type(children) is not list: return ERRORS.BAD_REQUEST main_domaine: Domaine = Domaine.query.filter_by( id_domaine=main).one_or_none() if not main_domaine: return ERRORS.DOMAIN_NOT_FOUND children_domains: List[Domaine] = [] for c in children: if type(c) is not int: return ERRORS.BAD_REQUEST ent = Domaine.query.filter_by(id_domaine=c).one_or_none() if not ent: return ERRORS.DOMAIN_NOT_FOUND children_domains.append(ent) # For each domain relied to children_domains, set main_domaine for c in children_domains: Stage.query.filter_by(id_domaine=c.id_domaine).update( {'id_domaine': main_domaine.id_domaine}) Emploi.query.filter_by(id_domaine=c.id_domaine).update( {'id_domaine': main_domaine.id_domaine}) # Delete every children domain for c in children_formations: db_session.delete(c) db_session.commit() return ""
def merge_formations(): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'main', 'children'} <= set(data): return ERRORS.MISSING_PARAMETERS main, children = data['main'], data['children'] if type(main) is not int or type(children) is not list: return ERRORS.BAD_REQUEST main_formation: Formation = Formation.query.filter_by( id_form=main).one_or_none() if not main_formation: return ERRORS.FORMATION_NOT_FOUND children_formations: List[Formation] = [] for c in children: if type(c) is not int: return ERRORS.BAD_REQUEST ent = Formation.query.filter_by(id_form=c).one_or_none() if not ent: return ERRORS.FORMATION_NOT_FOUND children_formations.append(ent) # For each student relied to children_formations, set main_formation for c in children_formations: Etudiant.query.filter_by(reorientation=c.id_form).update( {'reorientation': main_formation.id_form}) Etudiant.query.filter_by(cursus_anterieur=c.id_form).update( {'cursus_anterieur': main_formation.id_form}) # Delete every children company for c in children_formations: db_session.delete(c) db_session.commit() return ""
def delete_contact(id: int): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS c = Contact.query.filter_by(id_contact=id).one_or_none() if not c: return "" Emploi.query.filter_by(id_contact=id).update({"id_contact": None}) Stage.query.filter_by(id_contact=id).update({"id_contact": None}) db_session.delete(c) db_session.commit() return ""
def delete_student(id: int): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS # Check if exists etu = Etudiant.query.filter_by(id_etu=id).one_or_none() if not etu: return "" Etudiant.query.filter_by(id_etu=id).delete() # delete cascade does not work?? Token.query.filter_by(id_etu=id).delete() db_session.commit() return ""
def modify_contact(): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'name', 'mail', 'id'} <= set(data): return ERRORS.MISSING_PARAMETERS name, mail, id_contact = data['name'], data['mail'], data['id'] if type(id_contact) is not int: return ERRORS.INVALID_INPUT_TYPE c: Contact = Contact.query.filter_by( id_contact=id_contact).one_or_none() if not c: return ERRORS.CONTACT_NOT_FOUND if type(name) is not str: return ERRORS.INVALID_INPUT_TYPE special_check = r"^[\w_ -]+$" if not re.match(special_check, name): return ERRORS.INVALID_INPUT_VALUE if type(mail) is not str: return ERRORS.INVALID_INPUT_TYPE email_catch = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" if not re.match(email_catch, mail): return ERRORS.INVALID_EMAIL # Create new contact c.mail = mail c.nom = name db_session.commit() return flask.jsonify(c)
def delete_company(id: int): if not is_teacher(): return ERRORS.INVALID_CREDENTIALS c: Entreprise = Entreprise.query.filter_by( id_entreprise=id).one_or_none() if not c: return "" # Delete all manuel Stage.query.filter_by(id_entreprise=id).delete() Emploi.query.filter_by(id_entreprise=id).delete() Contact.query.filter_by(id_entreprise=id).delete() db_session.delete(c) db_session.commit() return ""
def modify_formation(): r = get_request() if not is_teacher() or not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'branch', 'location', 'level', 'id'} <= set(data): return ERRORS.MISSING_PARAMETERS branch, location, level, id_formation = data['branch'], data[ 'location'], data['level'], data['id'] if type(id_formation) is not int: return ERRORS.INVALID_INPUT_TYPE # Check level: must be in ENUM f: Formation = Formation.query.filter_by( id_form=id_formation).one_or_none() if not f: return ERRORS.FORMATION_NOT_FOUND if type(branch) is not str: return ERRORS.INVALID_INPUT_TYPE f.filiere = branch # Query le lieu pr obtenir lat & long si lieu != location if f.lieu != location: f.lieu = location if type(level) is not str: return ERRORS.INVALID_INPUT_TYPE valid_levels = {"licence", "master", "phd", "other"} if level not in valid_levels: return ERRORS.UNEXPECTED_INPUT_VALUE f.niveau = level db_session.commit() return flask.jsonify(f)
def make_contact(): r = get_request() if not r.is_json: return ERRORS.BAD_REQUEST data = r.json if not {'name', 'mail', 'id_entreprise'} <= set(data): return ERRORS.MISSING_PARAMETERS name, mail, id_entreprise = data['name'], data['mail'], data[ 'id_entreprise'] ## Search for similar contact f = Contact.query.filter( and_(Contact.nom.ilike(f"{name}"), Contact.mail.ilike(f"{mail}"), Contact.id_entreprise.ilike(f"{id_entreprise}"))).all() if len(f): return flask.jsonify(f[0]), 200 #Check id_entreprise ent: Entreprise = Entreprise.query.filter_by( id_entreprise=id_entreprise).one_or_none() if not ent: return ERRORS.COMPANY_NOT_FOUND special_check = r"^[\w_ -]+$" if not re.match(special_check, name): return ERRORS.INVALID_INPUT_VALUE email_catch = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" if not re.match(email_catch, mail): return ERRORS.INVALID_EMAIL # Create new contact cont = Contact.create(nom=name, mail=mail, id_entreprise=id_entreprise) db_session.add(cont) db_session.commit() return flask.jsonify(cont), 201
def delete_internship(id: int): internship: Stage = Stage.query.filter_by(id_stage=id).one_or_none() if internship is None: return "" # 200 OK deleted stu = get_student_or_none() if not stu: return ERRORS.STUDENT_NOT_FOUND if not is_teacher() and stu.id_etu != internship.id_etu: return ERRORS.INVALID_CREDENTIALS # Properly delete internship (maybe cascade is not working) stu.refresh_update() db_session.delete(internship) db_session.commit() return ""
def invalidate_token(): r = get_request() token = r.headers.get('Authorization').replace('Bearer ', '', 1) if is_teacher(): Token.query.filter_by(token=token).delete() db_session.commit() return "" else: current_etu_id = get_user().id_etu t: Token = Token.query.filter_by(token=token).one_or_none() if not t: return ERRORS.NOT_FOUND if t.id_etu == current_etu_id: db_session.delete(t) db_session.commit() else: return ERRORS.INVALID_CREDENTIALS
def delete_formation(id: int): # Get logged etudiant if not is_teacher(): return ERRORS.INVALID_CREDENTIALS form: Formation = Formation.query.filter_by(id_form=id).one_or_none() if not form: return "" # Supprime les formations des étudiants for etu in Etudiant.query.filter_by(cursus_anterieur=id).all(): etu.cursus_anterieur = None for etu in Etudiant.query.filter_by(reorientation=id).all(): e.reorientation = None db_session.commit() return ""
def delete_job(id: int): job: Emploi = Emploi.query.filter_by(id_emploi=id).one_or_none() if job is None: return "" # 200 OK deleted stu = get_student_or_none() if not stu: return ERRORS.STUDENT_NOT_FOUND if not is_teacher() and stu.id_etu != job.id_etu: return ERRORS.INVALID_CREDENTIALS # Properly delete job (maybe cascade is not working) stu.refresh_update() db_session.delete(job) db_session.commit() return ""