def get(self): coord_mechanic = (23.44333, 23.4433) motos = MotoModel.get_all() motos_json = [m.json_mechaniclistmotos() for m in motos] result = MotoModel.compute_distance(motos_json, coord_mechanic, "distance") return result
def create_test_moto(): new_moto = MotoModel.query.filter(MotoModel.matricula == matricula).first() # Si ya existe retornamos directamente if new_moto is not None: return new_moto # Si no existe la creamos new_moto = MotoModel(state="AVAILABLE", matricula=matricula, date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=23.4434, last_coordinate_longitude=23.4433, km_restantes=120.0, km_totales=500.0, date_last_check="18/10/2020", km_last_check=0.0) new_moto.save_to_db() new_moto = MotoModel.query.filter(MotoModel.matricula == matricula).first() if new_moto is None: # No se ha añadido a la base de datos!!!! # Si esto no funciona los tests no tienen sentido. assert False return new_moto
def delete(self, id): try: moto = MotoModel.find_by_id(id) # Si no se encuentra... if moto is None: return { 'message_status': 'Not Found', 'message': 'Motorbike with id [{}] not found'.format(id) }, 404 if moto.state in ("ACTIVE", "RESERVED"): return { 'message_status': 'Conflict', 'message': 'Motorbike with id [{}] is {} and can not be deleted'. format(id, moto.state.lower()) }, 409 MotoModel.delete_from_db(moto) return { 'message_status': 'Ok', 'message': 'Motorbike with id [{}] deleted successfully.'.format(id) }, 200 except: return { 'message_status': 'Internal Error', 'message': 'Internal Server Error during Delete Moto.' }, 500
def test_ModifyMoto_updateFields(): """ GIVEN a MotoModel model WHEN a MotoModel is updated THEN check the fields is updated correctly """ new_moto = MotoModel(state="REPAIRING", matricula="1234-MMM", date_estreno="24/11/2020", model_generic="premium", last_coordinate_latitude=23.4434, last_coordinate_longitude=23.4433, km_restantes=120.0, km_totales=10.0, date_last_check="24/11/2020", km_last_check=0.0) MotoModel.set_moto(new_moto, "1234-AAA", 110.0, "AVAILABLE") assert new_moto.matricula == "1234-AAA" assert new_moto.km_restantes == 110.0 assert new_moto.state == "AVAILABLE" assert new_moto.km_last_check == 10.0 date_format = "%d/%m/%Y" today = datetime.now().strftime(date_format) assert isinstance(today, str) assert isinstance(new_moto.date_last_check, str) assert new_moto.date_last_check == today
def get(self): parser = reqparse.RequestParser() parser.add_argument('client_coordinate_latitude', type=float, required=True, help="This field cannot be left blank") parser.add_argument('client_coordinate_longitude', type=float, required=True, help="This field cannot be left blank") parser.add_argument('model_generic', type=str, required=True, help="This field cannot be left blank") parser.add_argument('more_km_restantes', type=int, required=True, help="This field cannot be left blank") data = parser.parse_args() # Parámetros que pueden ser útiles en el futuro: # parser.add_argument('max_distance_m', type=float) coord_client = (data["client_coordinate_latitude"], data["client_coordinate_longitude"]) # Aquí se empieza con las condiciones resultantes de los filtros. list_and = [] # Para el cliente siempre queremos las AVAILABLE list_and.append(MotoModel.state == "AVAILABLE") # El caso sin filtro es data["more_km_restantes"]==0 if data["more_km_restantes"] > 0: list_and.append(MotoModel.km_restantes > data["more_km_restantes"]) # El caso sin filtro es data["model_generic"]=="all" if data["model_generic"] in ("premium", "basic"): list_and.append(MotoModel.model_generic == data['model_generic']) # En esta función juntamos todas las condiciones en una sucesión de AND's cond_final = MotoModel.condiciones_AND(list_and) # Hacemos la query en base a los filtros (condiciones previas) motos = MotoModel.query.filter(cond_final).all() # Hacemos una lista de jsons para enviarselo a la funcion compute_distance motos_json = [m.json_listmotos() for m in motos] # Calculamos las distancias y las añadimos a cada moto result = MotoModel.compute_distance(motos_json, coord_client, "distance") return result
def get(self, id): coord_mechanic = (23.44333, 23.4433) try: moto = MotoModel.find_by_id(id) moto_json = [moto.json_mechanicMoto()] result = MotoModel.compute_distance(moto_json, coord_mechanic, "distance") # los cambios de keyname de jsons es para coordinar con frontend return {'mechanic_moto': result['motos'][0]}, 200 except: return {"message": "Error Get Moto"}, 500
def put(self, id): parser = reqparse.RequestParser() parser.add_argument('matricula', type=str, required=True, help="This field cannot be left blank") parser.add_argument('km_restantes', type=float, required=True, help="This field cannot be left blank") parser.add_argument('state', type=str, required=True, help="This field cannot be left blank") data = parser.parse_args() moto = MotoModel.find_by_id(id) if (moto): moto_aux = MotoModel.find_by_matricula(data['matricula']) if (moto_aux is not None and moto.id != moto_aux.id): return { 'message': "Motorbike with license plate [{}] already exists".format( data['matricula']) }, 409 else: if ((data['km_restantes'] <= 5.0 and data['state'] == "AVAILABLE") or (data['km_restantes'] > 5.0 and data['state'] == "LOW_BATTERY_FUEL")): return { 'message': "State and the battery fields are not consistent" }, 400 try: moto.set_moto(data['matricula'], data['km_restantes'], data['state']) MotoModel.save_to_db(moto) return {"message": "Motorbike modified successfully"}, 200 except: return { "message": "Error while trying to modify motorbike with id [{}]". format(id) }, 500 else: return { 'message': "Motorbike with id [{}] Not Found".format(id) }, 404
def get(self, client_email): try: client = ClientModel.find_by_email(client_email) if client is not None: rr = ReservedRunningModel.find_by_client(client.client_id) # Compruebo si ha encontrado la reserva del ciente if rr is not None: # Compruebo si el estado de la moto es el correcto (ACTIVE) if rr.isActive(): # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): coord_client = (23.44333, 23.4433) moto = rr.moto moto_json = [moto.json_clientMoto()] result = MotoModel.compute_distance(moto_json, coord_client, "distance") # los cambios de keyname de jsons es para coordinar con frontend return {'start_moto': result['motos'][0]}, 201 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {'message': "Error Moto state isn't active"}, 500 else: return {'message': "Error Client haven't start moto"}, 404 else: return {'message': "Error Client Not Found"}, 404 except: return {"message": "Error Get Start Moto"}, 500
def delete(self, email_client): parser = reqparse.RequestParser() parser.add_argument('password', type=str, required=True, help="Password cannot be left blanck") data = parser.parse_args() password = data['password'] c = ClientModel.find_by_email(email_client) if c: # Si existe el cliente if c.password == password: # Si la password coincide con la del cliente rr = ReservedRunningModel.find_by_client(c.client_id) if(rr is not None): # Si existe una reserva o start afiliada al cliente, indagamos moto = MotoModel.find_by_id(rr.moto.id) if(moto.state == "RESERVED"): # Si la moto esta reservada # Borramos la fila de rr rr.delete_from_db() # Actualizamos el estado de la moto moto.state = "AVAILABLE" moto.save_to_db() # Borramos el cliente c.delete_from_db() return {"message": "Client DELETED successfully"}, 200 if(moto.state == "ACTIVE"): # No podemos borrar el cliente porque antes tiene que finalizar el trayecto return {'message': 'The account cannot be deleted because you have a journey started'}, 401 else: # Si no existe reserva o start, podemos borrarlo directamente c.delete_from_db() return {"message": "Client DELETED successfully"}, 200 else: # Password erronea return {'message': 'ERROR: The password is not correct.'}, 400 else: # Si no existe el cliente return {'message': 'ERROR: There is no client with email [{}] .'.format(email_client)}, 404
def delete(self, client_email, moto_id): try: moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # En caso de que tanto la moto y el cliente existan en sus respectivas tablas if moto is not None and client is not None: moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: reserve = ReservedRunningModel.query.filter(and_( ReservedRunningModel.clientId == client.client_id, ReservedRunningModel.motoId == moto_id )).first() # Si no se encuentra la reserva con esas características... if reserve is None: return {"message": "DELETE ERROR. Moto reserved with id {} and client {} not found.".format( moto_id, client_email)}, 404 # En caso de que si que exista una fila en la tabla RR... else: # Comprobamos cual es el auténtico estado de la moto. # una reserva(state =="RESERVED"), if moto.state == 'RESERVED': # Borramos la fila de rr reserve.delete_from_db() # Actualizamos el estado de la moto moto.state = "AVAILABLE" moto.save_to_db() return {"message": "Reserved Moto DELETED successfully"}, 200 # una running (state =="ACTIVE") elif moto.state == 'ACTIVE': # No se puede cancelar la reserva si no está reservada, sinó running(ACTIVE) return {"message": "DELETE ERROR Moto Reserve: Moto is ACTIVE"}, 500 # un DESASTRE (state ==otra cosa, que no debería). else: # ¡¡¡¡ERROR FATAL!!!! # Si entramos en este else es que la moto no debería estar en esta tabla. # TODO Revisar si deberíamos borrarlo igualmente return {"message": "FATAL Error. DELETE Moto Reserve: Moto is {}.".format(moto.state)}, 500 # En caso de que o la moto o el cliente NO EXISTAN en sus respectivas tablas else: return {"message": "DELETE ERROR Moto Reserve. Moto with id [{}] or client with email [{}] not found." .format(moto_id, client_email)}, 404 except: return {"message": "DELETE ERROR Reserved Moto. Internal Failure."}, 500
def test_ClientMotoList3_DistanciaMaximaPequeña(): lista_motos = [m1, m2, m3, m4] json_motos = [m.json_listmotos() for m in lista_motos] keyword = "distance" distancia_maxima = 100 coord = (22.9, 22.9) respuesta = MotoModel.compute_distance(json_motos, coord, keyword, distancia_maxima) assert "motos" in respuesta.keys() #esperamos una lista vacía, dado que la distancia es menor que la mínima assert len(respuesta["motos"]) == 0
def get(self, id): parser = reqparse.RequestParser() parser.add_argument('client_coordinate_latitude', type=float, required=True, help="This field cannot be left blank") parser.add_argument('client_coordinate_longitude', type=float, required=True, help="This field cannot be left blank") data = parser.parse_args() coord_client = (data["client_coordinate_latitude"], data["client_coordinate_longitude"]) try: moto = MotoModel.find_by_id(id) moto_json = [moto.json_clientMoto()] result = MotoModel.compute_distance(moto_json, coord_client, "distance") # los cambios de keyname de jsons es para coordinar con frontend return {'client_moto': result['motos'][0]}, 200 except: return {"message": "Error Get Moto"}, 500
def test_ClientMotoList1_Basico(): lista_motos = [m1, m2, m3, m4] json_motos = [m.json_listmotos() for m in lista_motos] keyword = "distance" coord = (22.9, 22.9) respuesta = MotoModel.compute_distance(json_motos, coord, keyword) assert "motos" in respuesta.keys() dist_anterior = 0 for r in respuesta["motos"]: distancia = r[keyword] # Esto es que está ordenada la lista assert dist_anterior <= distancia # Esto es que esté redondeado sin decimales assert distancia % 1 == 0 dist_anterior = distancia
def post(self, moto_id): try: moto = MotoModel.find_by_id(moto_id) if moto is not None: if moto.state == "RESERVED" or moto.state == "ACTIVE": rr = ReservedRunningModel.find_by_moto(moto.id) rr.delete_from_db() moto.set_state("ALERT") return {"message": "Correctly reported error"}, 201 else: moto.set_state("ALERT") return {"message": "Correctly reported error"}, 201 else: return {"message": "Moto not found"}, 404 except: return {"message": "Internal error when reporting the error"}, 500
def get(self, client_email): try: client = ClientModel.find_by_email(client_email) # Compruebo si ha encontrado el cliente con ese email if client is not None: rr = ReservedRunningModel.find_by_client(client.client_id) # Compruebo si ha encontrado la reserva del ciente if rr is not None: # Compruebo el estado de la moto if rr.isReserved(): # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): coord_client = (23.44333, 23.4433) moto = rr.moto moto_json = [moto.json_clientMoto()] result = MotoModel.compute_distance(moto_json, coord_client, "distance") # los cambios de keyname de jsons es para coordinar con frontend remaining_time = rr.make_remaining_time() if remaining_time.minute < 10: time_min = "0" + str(remaining_time.minute) else: time_min = str(remaining_time.minute) if remaining_time.hour < 10: time_h = "0" + str(remaining_time.hour) else: time_h = str(remaining_time.hour) return {'reserved_moto': result['motos'][0], "message": "You have until {}:{}h to start the motorbike".format(time_h, time_min), "remaining_time": time_h + ":" + time_min}, 201 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {"message": "ERROR RESERVED MOTO. Moto state isn't RESERVED, moto state = [{}]".format( rr.moto.state)}, 500 else: return {"message": "ERROR RESERVED MOTO. Error Client [{}] haven't reserved moto".format( client.client_id)}, 404 else: return {"message": "ERROR RESERVED MOTO. Error Client Not Found"}, 404 except: return {"message": "ERROR RESERVED MOTO. Error Get Reserved Moto"}, 500
def test_street_variable(): """ GIVEN a MotoModel model WHEN a new MotoModel is created THEN check the address field is defined correctly """ new_moto = MotoModel(state="ACTIVE", matricula="1234-MMM", date_estreno="24/11/2020", model_generic="premium", last_coordinate_latitude=23.4434, last_coordinate_longitude=23.4433, km_restantes=120.0, km_totales=0.0, date_last_check="24/11/2020", km_last_check=0.0) assert new_moto.address == "Al Kufrah, Libia"
def put(self, client_email, moto_id): try: moto = MotoModel.query.filter(MotoModel.id == moto_id).first() client = ClientModel.query.filter(ClientModel.email == client_email).first() if moto is not None and client is not None: r = ReservedRunningModel.query.filter(and_( ReservedRunningModel.motoId == moto_id, ReservedRunningModel.clientId == client.client_id)).first() if r is not None and moto.state == "ACTIVE": # En caso de que exista y de que este ACTIVE # Aquí simulamos un par de cosas para aumentar el realismo de la versión de prueba old_coord = moto.last_coordinate_latitude, moto.last_coordinate_longitude # Unas nuevas coordenadas (Aleatorias) new_coord = MotoModel.get_random_coordinates(coord=old_coord, std_deviation = 0.0015 * moto.km_restantes) # Calculamos los km_recorridos basándonos en las coordenadas # (y poniendo un extra random, suponiendo trayectorias no rectas). km_recorridos = moto.compute_km_recorridos(new_coord) # Actualizamos todó lo necesario moto.km_totales += km_recorridos moto.km_restantes -= km_recorridos if moto.hasLowBattery(): moto.state = 'LOW_BATTERY_FUEL' else: moto.state = "AVAILABLE" moto.updateCoordAndAddress(new_coord) moto.save_to_db() r.delete_from_db() return {'message_status': 'Ok', 'message': 'Motorbike stoped successfully'},200 return {'message_status': "Not Found", 'message': "Client with email {} is not riding motorbike with id [{}]. " .format(client_email, moto_id)}, 404 except: return {'message_status': "Internal Error", 'message': "Internal Server Error. "}, 500
def post(self): parser = reqparse.RequestParser() parser.add_argument('license_plate', type=str, required=True, help="This field cannot be left blank") parser.add_argument('model_generic', type=str, required=True, help="This field cannot be left blank") data = parser.parse_args() matricula = data["license_plate"].upper() model_generic = data["model_generic"] if not MotoModel.is_license_plate(matricula): return { "message": "ERROR: The format of the license plate is not valid." }, 400 if model_generic not in ("basic", "premium"): return { "message": "ERROR: model_generic should be either [basic] or [premium]." }, 400 m = MotoModel.query.filter( MotoModel.matricula == data["license_plate"]).first() if m is not None: return { "message": "There is already a motorbike with license plate [{}].".format( matricula) }, 409 else: try: date_format = "%d/%m/%Y" today = datetime.now().strftime(date_format) str_today = today # str(today.day) + str(today.month) + str(today.year) # Esto de aquí genera unas coordenadas en BCN con ruido gausiano. latt, long = MotoModel.get_random_coordinates() moto = MotoModel('AVAILABLE', matricula, str_today, data['model_generic'], latt, long, 50, 0, str_today, 0) moto.save_to_db() return {"message": "Moto added successfully"}, 200 except: return {"message": "Internal Error Post Moto"}, 500
def post(self): parser = reqparse.RequestParser() parser.add_argument('client_email', type=str, required=True, help="Client email cannot be left blank") parser.add_argument('moto_id', type=int, required=True, help="Moto id cannot be left blank") data = parser.parse_args() client_email = data['client_email'] moto_id = data['moto_id'] moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: # Compruebo si el estado de la moto es el correcto (AVAILABLE) if moto.state == 'AVAILABLE': # Compruebo si el cliente no tiene motos reservadas if ReservedRunningModel.find_by_client(client.client_id) is None: rr = ReservedRunningModel(client, moto) ReservedRunningModel.save_to_db(rr) ReservedRunningModel.update_state_reserved(rr) remaining_time = rr.make_remaining_time() if remaining_time.minute < 10: time_min = "0" + str(remaining_time.minute) else: time_min = str(remaining_time.minute) if remaining_time.hour < 10: time_h = "0" + str(remaining_time.hour) else: time_h = str(remaining_time.hour) return {"message": "You have until {}:{}h to start the motorbike".format(time_h, time_min), "remaining_time": time_h + ":" + time_min}, 201 else: return {"message": "ERROR RESERVED MOTO. Customer [{}] already has a reserved motorcycle".format( client.client_id)}, 500 else: return {"message": "ERROR RESERVED MOTO. Moto state isn't AVAILABLE, moto state = [{}]".format( moto.state)}, 500 else: return {"message": "ERROR RESERVED MOTO. Motorcycle error or client not found for Reserved Moto post"}, 404
def post(self): try: parser = reqparse.RequestParser() parser.add_argument('client_email', type=str, required=True, help="Client email cannot be left blank") parser.add_argument('moto_id', type=int, required=True, help="Moto id cannot be left blank") data = parser.parse_args() client_email = data['client_email'] moto_id = data['moto_id'] moto = MotoModel.find_by_id(moto_id) client = ClientModel.find_by_email(client_email) rr = ReservedRunningModel.find_by_client_moto(client.client_id, moto_id) # Compruebo si existe el cliente segun el email recibido y si existe la moto segun el id recibido if moto is not None and client is not None: # Compruebo si el estado de la moto es el correcto (RESERVED) if moto.state == 'RESERVED': # Compruebo si ha encontrado la reserva del ciente y la moto if rr is not None: # Compruebo que no se ha superado el tiempo limite para el start moto desde la reserva if rr.check_remaining_time(): ReservedRunningModel.make_star_moto(rr) ReservedRunningModel.update_state_start(rr) return {"message": "Start successfully"}, 200 else: ReservedRunningModel.update_state_available(rr) ReservedRunningModel.delete_from_db(rr) return {"message": "The time limit for the start has expired"}, 500 else: return {"message": "Reservation error with that id_client and id_moto does not exist"}, 500 else: return {"message": "Error state moto isn't RESERVED"}, 500 else: return {"message": "Motorcycle or client not found error for POST Start Moto"}, 404 except: return {"message": "Error POST Start Moto"}, 500
def get(self, id): try: moto = MotoModel.find_by_id(id) return {'moto': moto.json()}, 200 except: return {"message": "Error Get Moto"}, 500
# coding=utf-8 import math import app from models.moto_model import MotoModel from datetime import datetime # Test m1 = MotoModel(state="ACTIVE", matricula="3333-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=23., last_coordinate_longitude=23., km_restantes=120.0, km_totales=0.0, date_last_check="18/10/2020", km_last_check=0.0) m2 = MotoModel(state="ACTIVE", matricula="4444-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=23.1, last_coordinate_longitude=23.1, km_restantes=120.0, km_totales=0.0, date_last_check="18/10/2020", km_last_check=0.0)
def init_db(): db.drop_all() db.create_all() new_moto1 = MotoModel(state="AVAILABLE", matricula="1111-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.403193, last_coordinate_longitude=2.175004, km_restantes=34.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto1) new_moto2 = MotoModel(state="AVAILABLE", matricula="2222-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.403719, last_coordinate_longitude=2.189128, km_restantes=3.0, km_totales=23.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto2) new_moto3 = MotoModel(state="AVAILABLE", matricula="3333-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.386399, last_coordinate_longitude=2.164143, km_restantes=120.0, km_totales=500.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto3) new_moto = MotoModel(state="AVAILABLE", matricula="4444-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.348788, last_coordinate_longitude=2.132925, km_restantes=45.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel(state="LOW_BATTERY_FUEL", matricula="5555-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.413273, last_coordinate_longitude=2.152931, km_restantes=2.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="LOW_BATTERY_FUEL", matricula="6666-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.427691, last_coordinate_longitude=2.166293, km_restantes=4.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="7777-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.387818, last_coordinate_longitude=2.169647, km_restantes=23.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="8888-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.375960, last_coordinate_longitude=2.177455, km_restantes=35.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="5454-MMM", date_estreno="28/11/2020", model_generic="premium", last_coordinate_latitude=41.384223, last_coordinate_longitude=2.160337, km_restantes=35.0, km_totales=403.0, date_last_check="28/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel(state="AVAILABLE", matricula="4545-MMM", date_estreno="28/11/2020", model_generic="premium", last_coordinate_latitude=41.359768, last_coordinate_longitude=2.084035, km_restantes=35.0, km_totales=403.0, date_last_check="28/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto9 = MotoModel(state="AVAILABLE", matricula="9999-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.591158, last_coordinate_longitude=1.520865, km_restantes=34.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto9) new_moto10 = MotoModel(state="AVAILABLE", matricula="1010-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.591158, last_coordinate_longitude=1.5209, km_restantes=999.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto10) client1 = ClientModel(nombre="Juana", iban="2223462362665251w", dni_nie="11111111J", email="*****@*****.**", password="******") db.session.add(client1) client2 = ClientModel(nombre="Camila", iban="22462362665251w", dni_nie="14441111J", email="*****@*****.**", password="******") db.session.add(client2) client3 = ClientModel(nombre="Sofia", iban="2223332362665251w", dni_nie="11188881J", email="*****@*****.**", password="******") db.session.add(client3) client = ClientModel(nombre="Ramona", iban="225554362665251w", dni_nie="12341111J", email="*****@*****.**", password="******") db.session.add(client) articulo = ArticleModel( titulo="¡Motos más nuevas y potentes que nunca!", texto="Las nuevas motos de Mooving están batiendo todos los" "récord habidos y por haber. Tenemos más de 400 motos eléctricas" "con una autonomía de más de 100KM.", fecha_creacion="2020/10/29", visible=True) db.session.add(articulo) articulo = ArticleModel( titulo="¡Motos más rápidas !", texto= "Las nuevas motos de Mooving son más rápidas que las de la competencia." " Tenemos más de 400 motos eléctricas" " con una velocidad punta de más de 100KM/H .", fecha_creacion="2020/10/28", visible=True) db.session.add(articulo) new_mechanic = MechanicModel(name="Jose", subname="De carglass", dni="11111111J", password="******", date_registration="23/02/2020") db.session.add(new_mechanic) new_mechanic = MechanicModel(name="Pepe", subname="De marcota", dni="22222222J", password="******", date_registration="24/02/2020") db.session.add(new_mechanic) db.session.commit() print('Success in adding items to database')
def add_data(db=db): new_moto1 = MotoModel( state="AVAILABLE", matricula="1111-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.40181444604073, last_coordinate_longitude=2.1602937877348554, km_restantes=80.0, km_totales=300.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto1) new_moto2 = MotoModel( state="AVAILABLE", matricula="2222-MMM", date_estreno="28/10/2020", model_generic="basic", last_coordinate_latitude=41.40514485607213, last_coordinate_longitude=2.1587408287276393, km_restantes=80.0, km_totales=23.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto2) new_moto3 = MotoModel( state="AVAILABLE", matricula="3333-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.40396129395845, last_coordinate_longitude=2.1672429122257184, km_restantes=120.0, km_totales=500.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto3) new_moto = MotoModel( state="AVAILABLE", matricula="4444-MMM", date_estreno="28/10/2020", model_generic="premium", last_coordinate_latitude=41.403205972568855, last_coordinate_longitude=2.155472976562771, km_restantes=120.0, km_totales=203.0, date_last_check="18/10/2020", km_last_check=0.0) db.session.add(new_moto) new_moto = MotoModel( state="LOW_BATTERY_FUEL", matricula="5555-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.40510495456656, last_coordinate_longitude=2.166668308564227, km_restantes=30.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) new_moto = MotoModel( state="LOW_BATTERY_FUEL", matricula="6666-MMM", date_estreno="08/10/2020", model_generic="premium", last_coordinate_latitude=41.40551322372631, last_coordinate_longitude=2.163830433113226 , km_restantes=30.0, km_totales=100.0, date_last_check="18/10/2020", km_last_check=100.0) db.session.add(new_moto) client1 = ClientModel( nombre="Juana", iban="2223462362665251w", dni_nie="11111111J", email="*****@*****.**", password="******" ) db.session.add(client1) client2 = ClientModel( nombre="Camila", iban="22462362665251w", dni_nie="14441111J", email="*****@*****.**", password="******" ) db.session.add(client2) client3 = ClientModel( nombre="Sofia", iban="2223332362665251w", dni_nie="11188881J", email="*****@*****.**", password="******" ) db.session.add(client3) client = ClientModel( nombre="Ramona", iban="225554362665251w", dni_nie="12341111J", email="*****@*****.**", password="******" ) db.session.add(client) articulo = ArticleModel( titulo="¡Motos más nuevas y potentes que nunca!", texto="Las nuevas motos de Mooving están batiendo todos los" "récord habidos y por haber. Tenemos más de 400 motos eléctricas" "con una autonomía de más de 100KM.", fecha_creacion="2020/10/29", visible=True) db.session.add(articulo) articulo = ArticleModel( titulo="¡Motos más rápidas !", texto="Las nuevas motos de Mooving son más rápidas que las de la competencia." " Tenemos más de 400 motos eléctricas" " con una velocidad punta de más de 100KM/H .", fecha_creacion="2020/10/28", visible=True) db.session.add(articulo) new_mechanic = MechanicModel( name="Jose", subname="De carglass", dni="11111111J", password="******", date_registration="23/02/2020") db.session.add(new_mechanic) new_mechanic = MechanicModel( name="Pepe", subname="De marcota", dni="22222222J", password="******", date_registration="24/02/2020") db.session.add(new_mechanic) db.session.commit() print('Success in adding items to database')