From 77efcc2e4c5405ce52b1641c4ff18babf1bb1748 Mon Sep 17 00:00:00 2001 From: GabrielBarberini Date: Fri, 24 May 2024 00:04:24 -0300 Subject: [PATCH] implements db context manager --- lib/controllers/environment.py | 16 ++++++---- lib/controllers/flight.py | 52 ++++++++++++++++++--------------- lib/controllers/motor.py | 21 ++++++------- lib/controllers/rocket.py | 27 ++++++++++------- lib/repositories/environment.py | 32 +++++++++++--------- lib/repositories/flight.py | 30 ++++++++++--------- lib/repositories/motor.py | 32 +++++++++++--------- lib/repositories/repo.py | 9 +++++- lib/repositories/rocket.py | 29 +++++++++--------- 9 files changed, 143 insertions(+), 105 deletions(-) diff --git a/lib/controllers/environment.py b/lib/controllers/environment.py index e9de748..f857415 100644 --- a/lib/controllers/environment.py +++ b/lib/controllers/environment.py @@ -70,7 +70,8 @@ async def create_env(self) -> Union[EnvCreated, HTTPException]: views.EnvCreated """ try: - await EnvRepository.fetch_env(self.env).create_env() + with EnvRepository.fetch_env(self.env) as env_repo: + await env_repo.create_env() except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.environment.create_env: {exc_str}") @@ -100,7 +101,9 @@ async def get_env_by_id(env_id: str) -> Union[Env, HTTPException]: HTTP 404 Not Found: If the env is not found in the database. """ try: - read_env = await EnvRepository().get_env_by_id(env_id) + with EnvRepository() as env_repo: + await env_repo.get_env_by_id(env_id) + read_env = env_repo.env except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.environment.get_env_by_id: {exc_str}") @@ -176,8 +179,9 @@ async def update_env_by_id( HTTP 404 Not Found: If the env is not found in the database. """ try: - env_repo = await EnvRepository.fetch_env(self.env).create_env() - await env_repo.delete_env_by_id(env_id) + with EnvRepository.fetch_env(self.env) as env_repo: + await env_repo.create_env() + await env_repo.delete_env_by_id(env_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.environment.update_env: {exc_str}") @@ -209,7 +213,8 @@ async def delete_env_by_id( HTTP 404 Not Found: If the env is not found in the database. """ try: - await EnvRepository().delete_env_by_id(env_id) + with EnvRepository() as env_repo: + await env_repo.delete_env_by_id(env_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.environment.delete_env: {exc_str}") @@ -243,6 +248,7 @@ async def simulate_env( try: read_env = await cls.get_env_by_id(env_id) rocketpy_env = cls.get_rocketpy_env(read_env) + env_simulation_numbers = EnvData.parse_obj( rocketpy_env.all_info_returned() ) diff --git a/lib/controllers/flight.py b/lib/controllers/flight.py index eae8486..8546cb3 100644 --- a/lib/controllers/flight.py +++ b/lib/controllers/flight.py @@ -107,9 +107,11 @@ async def create_flight(self) -> Union[FlightCreated, HTTPException]: views.FlightCreated """ try: - await FlightRepository.fetch_flight(self.flight).create_flight( - motor_kind=self.motor_kind, rocket_option=self.rocket_option - ) + with FlightRepository.fetch_flight(self.flight) as flight_repo: + await flight_repo.create_flight( + motor_kind=self.motor_kind, + rocket_option=self.rocket_option, + ) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.flight.create_flight: {exc_str}") @@ -139,7 +141,9 @@ async def get_flight_by_id(flight_id: str) -> Union[Flight, HTTPException]: HTTP 404 Not Found: If the flight is not found in the database. """ try: - read_flight = await FlightRepository().get_flight_by_id(flight_id) + with FlightRepository() as flight_repo: + await flight_repo.get_flight_by_id(flight_id) + read_flight = flight_repo.flight except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.flight.get_flight_by_id: {exc_str}") @@ -215,12 +219,12 @@ async def update_flight_by_id( HTTP 404 Not Found: If the flight is not found in the database. """ try: - flight_repo = await FlightRepository.fetch_flight( - self.flight - ).create_flight( - motor_kind=self.motor_kind, rocket_option=self.rocket_option - ) - await flight_repo.delete_flight_by_id(flight_id) + with FlightRepository.fetch_flight(self.flight) as flight_repo: + await flight_repo.create_flight( + motor_kind=self.motor_kind, + rocket_option=self.rocket_option, + ) + await flight_repo.delete_flight_by_id(flight_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.flight.update_flight: {exc_str}") @@ -257,13 +261,12 @@ async def update_env_by_flight_id( new_flight = read_flight.dict() new_flight["environment"] = env new_flight = Flight(**new_flight) - flight_repo = await FlightRepository.fetch_flight( - new_flight - ).create_flight( - motor_kind=read_flight.rocket.motor.motor_kind, - rocket_option=read_flight.rocket.rocket_option, - ) - await flight_repo.delete_flight_by_id(flight_id) + with FlightRepository.fetch_flight(new_flight) as flight_repo: + await flight_repo.create_flight( + motor_kind=read_flight.rocket.motor.motor_kind, + rocket_option=read_flight.rocket.rocket_option, + ) + await flight_repo.delete_flight_by_id(flight_id) except HTTPException as e: raise e from e except Exception as e: @@ -305,10 +308,11 @@ async def update_rocket_by_flight_id( new_flight = read_flight.dict() new_flight["rocket"] = updated_rocket new_flight = Flight(**new_flight) - flight_repo = await FlightRepository.fetch_flight( - new_flight - ).create_flight(motor_kind=motor_kind, rocket_option=rocket_option) - await flight_repo.delete_flight_by_id(flight_id) + with FlightRepository.fetch_flight(new_flight) as flight_repo: + await flight_repo.create_flight( + motor_kind=motor_kind, rocket_option=rocket_option + ) + await flight_repo.delete_flight_by_id(flight_id) except HTTPException as e: raise e from e except Exception as e: @@ -342,7 +346,8 @@ async def delete_flight_by_id( HTTP 404 Not Found: If the flight is not found in the database. """ try: - await FlightRepository().delete_flight_by_id(flight_id) + with FlightRepository() as flight_repo: + await flight_repo.delete_flight_by_id(flight_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.flight.delete_flight: {exc_str}") @@ -376,8 +381,7 @@ async def simulate_flight( """ try: read_flight = await cls.get_flight_by_id(flight_id=flight_id) - rocketpy_flight = cls.get_rocketpy_flight(flight=read_flight) - flight = rocketpy_flight + flight = cls.get_rocketpy_flight(read_flight) _initial_conditions = InitialConditions( initial_altitude="Attitude - e0: {:.3f} | e1: {:.3f} | e2: {:.3f} | e3: {:.3f}".format( diff --git a/lib/controllers/motor.py b/lib/controllers/motor.py index ad67813..96c0487 100644 --- a/lib/controllers/motor.py +++ b/lib/controllers/motor.py @@ -118,9 +118,8 @@ async def create_motor(self) -> Union[MotorCreated, HTTPException]: views.MotorCreated """ try: - await MotorRepository.fetch_motor(self.motor).create_motor( - motor_kind=self.motor_kind - ) + with MotorRepository.fetch_motor(self.motor) as motor_repo: + await motor_repo.create_motor(motor_kind=self.motor_kind) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.motor.create_motor: {exc_str}") @@ -150,7 +149,9 @@ async def get_motor_by_id(motor_id: str) -> Union[Motor, HTTPException]: HTTP 404 Not Found: If the motor is not found in the database. """ try: - read_motor = await MotorRepository().get_motor_by_id(motor_id) + with MotorRepository() as motor_repo: + await motor_repo.get_motor_by_id(motor_id) + read_motor = motor_repo.motor except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.motor.get_motor_by_id: {exc_str}") @@ -226,10 +227,9 @@ async def update_motor_by_id( HTTP 404 Not Found: If the motor is not found in the database. """ try: - motor_repo = await MotorRepository.fetch_motor( - self.motor - ).create_motor(motor_kind=self.motor_kind) - await motor_repo.delete_motor_by_id(motor_id) + with MotorRepository.fetch_motor(self.motor) as motor_repo: + await motor_repo.create_motor(motor_kind=self.motor_kind) + await motor_repo.delete_motor_by_id(motor_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.motor.update_motor: {exc_str}") @@ -261,7 +261,8 @@ async def delete_motor_by_id( HTTP 404 Not Found: If the motor is not found in the database. """ try: - await MotorRepository().delete_motor_by_id(motor_id) + with MotorRepository() as motor_repo: + await motor_repo.delete_motor_by_id(motor_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.motor.delete_motor: {exc_str}") @@ -293,7 +294,7 @@ async def simulate_motor( HTTP 404 Not Found: If the motor does not exist in the database. """ try: - read_motor = await MotorRepository().get_motor_by_id(motor_id) + read_motor = await cls.get_motor_by_id(motor_id) motor = cls.get_rocketpy_motor(read_motor) motor_simulation_numbers = MotorData( diff --git a/lib/controllers/rocket.py b/lib/controllers/rocket.py index 73db781..8e9ccd5 100644 --- a/lib/controllers/rocket.py +++ b/lib/controllers/rocket.py @@ -155,9 +155,11 @@ async def create_rocket(self) -> Union[RocketCreated, HTTPException]: views.RocketCreated """ try: - await RocketRepository.fetch_rocket(self.rocket).create_rocket( - rocket_option=self.rocket_option, motor_kind=self.motor_kind - ) + with RocketRepository.fetch_rocket(self.rocket) as rocket_repo: + await rocket_repo.create_rocket( + rocket_option=self.rocket_option, + motor_kind=self.motor_kind, + ) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.rocket.create_rocket: {exc_str}") @@ -189,7 +191,9 @@ async def get_rocket_by_id( HTTP 404 Not Found: If the rocket is not found in the database. """ try: - read_rocket = await RocketRepository().get_rocket_by_id(rocket_id) + with RocketRepository() as rocket_repo: + await rocket_repo.get_rocket_by_id(rocket_id) + read_rocket = rocket_repo.rocket except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.rocket.get_rocket_by_id: {exc_str}") @@ -264,12 +268,12 @@ async def update_rocket_by_id( HTTP 404 Not Found: If the rocket is not found in the database. """ try: - rocket_repo = await RocketRepository.fetch_rocket( - self.rocket - ).create_rocket( - rocket_option=self.rocket_option, motor_kind=self.motor_kind - ) - await rocket_repo.delete_rocket_by_id(rocket_id) + with RocketRepository.fetch_rocket(self.rocket) as rocket_repo: + await rocket_repo.create_rocket( + rocket_option=self.rocket_option, + motor_kind=self.motor_kind, + ) + await rocket_repo.delete_rocket_by_id(rocket_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.rocket.update_rocket: {exc_str}") @@ -301,7 +305,8 @@ async def delete_rocket_by_id( HTTP 404 Not Found: If the rocket is not found in the database. """ try: - await RocketRepository().delete_rocket_by_id(rocket_id) + with RocketRepository() as rocket_repo: + await rocket_repo.delete_rocket_by_id(rocket_id) except Exception as e: exc_str = parse_error(e) logger.error(f"controllers.rocket.delete_rocket: {exc_str}") diff --git a/lib/repositories/environment.py b/lib/repositories/environment.py index 823d338..8983ec7 100644 --- a/lib/repositories/environment.py +++ b/lib/repositories/environment.py @@ -18,6 +18,7 @@ class EnvRepository(Repository): def __init__(self): super().__init__("environments") + self._env = None @classmethod def fetch_env(cls, environment: Env): @@ -42,6 +43,17 @@ def env_id(self) -> str: def env_id(self, env_id: "str"): self._env_id = env_id + async def insert_env(self, env_data: dict): + await self.collection.insert_one(env_data) + return self + + async def find_env(self, env_id: str): + return await self.collection.find_one({"env_id": env_id}) + + async def delete_env(self, env_id: str): + await self.collection.delete_one({"env_id": env_id}) + return self + async def create_env(self): """ Creates a non-existing models.Env in the database @@ -69,17 +81,18 @@ async def get_env_by_id(self, env_id: str) -> Union[Env, None]: Gets a models.Env from the database Returns: - models.Env + self """ try: read_env = await self.find_env(env_id) parsed_env = Env.parse_obj(read_env) if read_env else None + self.env = parsed_env except Exception as e: exc_str = parse_error(e) logger.error(f"repositories.environment.get_env: {exc_str}") raise Exception(f"Error getting environment: {exc_str}") from e else: - return parsed_env + return self finally: logger.info( f"Call to repositories.environment.get_env completed for Env {env_id}" @@ -90,7 +103,7 @@ async def delete_env_by_id(self, env_id: str): Deletes a models.Env from the database Returns: - None + self """ try: await self.delete_env(env_id) @@ -98,18 +111,9 @@ async def delete_env_by_id(self, env_id: str): exc_str = parse_error(e) logger.error(f"repositories.environment.delete_env: {exc_str}") raise Exception(f"Error deleting environment: {exc_str}") from e + else: + return self finally: logger.info( f"Call to repositories.environment.delete_env completed for Env {env_id}" ) - - async def insert_env(self, env_data: dict): - await self.collection.insert_one(env_data) - return self - - async def find_env(self, env_id: str): - return await self.collection.find_one({"env_id": env_id}) - - async def delete_env(self, env_id: str): - await self.collection.delete_one({"env_id": env_id}) - return self diff --git a/lib/repositories/flight.py b/lib/repositories/flight.py index 722fbcb..e2d476d 100644 --- a/lib/repositories/flight.py +++ b/lib/repositories/flight.py @@ -18,6 +18,7 @@ class FlightRepository(Repository): def __init__(self): super().__init__("flights") + self._flight = None @classmethod def fetch_flight(cls, flight: Flight): @@ -42,6 +43,16 @@ def flight_id(self) -> str: def flight_id(self, flight_id: "str"): self._flight_id = flight_id + async def insert_flight(self, flight_data: dict): + await self.collection.insert_one(flight_data) + + async def find_flight(self, flight_id: str): + return await self.collection.find_one({"flight_id": flight_id}) + + async def delete_flight(self, flight_id: str): + await self.collection.delete_one({"flight_id": flight_id}) + return self + async def create_flight( self, *, motor_kind: str = "SOLID", rocket_option: str = "CALISTO" ): @@ -77,19 +88,20 @@ async def get_flight_by_id(self, flight_id: str) -> Union[Flight, None]: Gets a models.Flight from the database Returns: - models.Flight + self """ try: read_flight = await self.find_flight(flight_id) parsed_flight = ( Flight.parse_obj(read_flight) if read_flight else None ) + self.flight = parsed_flight except Exception as e: exc_str = parse_error(e) logger.error(f"repositories.flight.get_flight: {exc_str}") raise Exception(f"Error getting flight: {exc_str}") from e else: - return parsed_flight + return self finally: logger.info( f"Call to repositories.flight.get_flight completed for Flight {flight_id}" @@ -100,7 +112,7 @@ async def delete_flight_by_id(self, flight_id: str): Deletes a models.Flight from the database Returns: - None + self """ try: await self.delete_flight(flight_id) @@ -108,17 +120,9 @@ async def delete_flight_by_id(self, flight_id: str): exc_str = parse_error(e) logger.error(f"repositories.flight.delete_flight: {exc_str}") raise Exception(f"Error deleting flight: {exc_str}") from e + else: + return self finally: logger.info( f"Call to repositories.flight.delete_flight completed for Flight {flight_id}" ) - - async def insert_flight(self, flight_data: dict): - await self.collection.insert_one(flight_data) - - async def find_flight(self, flight_id: str): - return await self.collection.find_one({"flight_id": flight_id}) - - async def delete_flight(self, flight_id: str): - await self.collection.delete_one({"flight_id": flight_id}) - return self diff --git a/lib/repositories/motor.py b/lib/repositories/motor.py index 9d21f13..b47bd7f 100644 --- a/lib/repositories/motor.py +++ b/lib/repositories/motor.py @@ -18,6 +18,7 @@ class MotorRepository(Repository): def __init__(self): super().__init__("motors") + self._motor = None @classmethod def fetch_motor(cls, motor: Motor): @@ -42,6 +43,17 @@ def motor_id(self) -> str: def motor_id(self, motor_id: "str"): self._motor_id = motor_id + async def insert_motor(self, motor_data: dict): + await self.collection.insert_one(motor_data) + return self + + async def find_motor(self, motor_id: str): + return await self.collection.find_one({"motor_id": motor_id}) + + async def delete_motor(self, motor_id: str): + await self.collection.delete_one({"motor_id": motor_id}) + return self + async def create_motor(self, motor_kind: str = "SOLID"): """ Creates a non-existing models.Motor in the database @@ -73,17 +85,18 @@ async def get_motor_by_id(self, motor_id: str) -> Union[motor, None]: Gets a models.Motor from the database Returns: - models.Motor + self """ try: read_motor = await self.find_motor(motor_id) parsed_motor = Motor.parse_obj(read_motor) if read_motor else None + self.motor = parsed_motor except Exception as e: exc_str = parse_error(e) logger.error(f"repositories.motor.get_motor: {exc_str}") raise Exception(f"Error getting motor: {exc_str}") from e else: - return parsed_motor + return self finally: logger.info( f"Call to repositories.motor.get_motor completed for Motor {motor_id}" @@ -94,7 +107,7 @@ async def delete_motor_by_id(self, motor_id: str): Deletes a models.Motor from the database Returns: - None + self """ try: await self.delete_motor(motor_id) @@ -102,18 +115,9 @@ async def delete_motor_by_id(self, motor_id: str): exc_str = parse_error(e) logger.error(f"repositories.motor.delete_motor: {exc_str}") raise Exception(f"Error deleting motor: {exc_str}") from e + else: + return self finally: logger.info( f"Call to repositories.motor.delete_motor completed for Motor {motor_id}" ) - - async def insert_motor(self, motor_data: dict): - await self.collection.insert_one(motor_data) - return self - - async def find_motor(self, motor_id: str): - return await self.collection.find_one({"motor_id": motor_id}) - - async def delete_motor(self, motor_id: str): - await self.collection.delete_one({"motor_id": motor_id}) - return self diff --git a/lib/repositories/repo.py b/lib/repositories/repo.py index 9044285..108c66d 100644 --- a/lib/repositories/repo.py +++ b/lib/repositories/repo.py @@ -41,6 +41,13 @@ def __init__(self, collection: str): "Could not establish a connection with MongoDB." ) from e + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + self.close_connection() + self._instances.pop(self.__class__) + @property def connection_string(self): return self._connection_string @@ -65,5 +72,5 @@ def collection(self): def collection(self, value): self._collection = value - async def close_connection(self) -> None: + def close_connection(self): self.client.close() diff --git a/lib/repositories/rocket.py b/lib/repositories/rocket.py index 8ae585d..b504eb4 100644 --- a/lib/repositories/rocket.py +++ b/lib/repositories/rocket.py @@ -42,6 +42,17 @@ def rocket_id(self) -> str: def rocket_id(self, rocket_id: "str"): self._rocket_id = rocket_id + async def insert_rocket(self, rocket_data: dict): + await self.collection.insert_one(rocket_data) + return self + + async def find_rocket(self, rocket_id: str): + return await self.collection.find_one({"rocket_id": rocket_id}) + + async def delete_rocket(self, rocket_id: str): + await self.collection.delete_one({"rocket_id": rocket_id}) + return self + async def create_rocket( self, *, rocket_option: str = "CALISTO", motor_kind: str = "SOLID" ): @@ -84,12 +95,13 @@ async def get_rocket_by_id(self, rocket_id: str) -> Union[Rocket, None]: parsed_rocket = ( Rocket.parse_obj(read_rocket) if read_rocket else None ) + self.rocket = parsed_rocket except Exception as e: exc_str = parse_error(e) logger.error(f"repositories.rocket.get_rocket: {exc_str}") raise Exception(f"Error getting rocket: {exc_str}") from e else: - return parsed_rocket + return self finally: logger.info( f"Call to repositories.rocket.get_rocket completed for Rocket {rocket_id}" @@ -100,7 +112,7 @@ async def delete_rocket_by_id(self, rocket_id: str): Deletes a models.Rocket from the database Returns: - None + self """ try: await self.delete_rocket(rocket_id) @@ -108,18 +120,9 @@ async def delete_rocket_by_id(self, rocket_id: str): exc_str = parse_error(e) logger.error(f"repositories.rocket.delete_rocket: {exc_str}") raise Exception(f"Error deleting rocket: {exc_str}") from e + else: + return self finally: logger.info( f"Call to repositories.rocket.delete_rocket completed for Rocket {rocket_id}" ) - - async def insert_rocket(self, rocket_data: dict): - await self.collection.insert_one(rocket_data) - return self - - async def find_rocket(self, rocket_id: str): - return await self.collection.find_one({"rocket_id": rocket_id}) - - async def delete_rocket(self, rocket_id: str): - await self.collection.delete_one({"rocket_id": rocket_id}) - return self