Skip to content

Commit 36253ab

Browse files
refactors controllers/environemnt
1 parent 243f39e commit 36253ab

File tree

2 files changed

+155
-83
lines changed

2 files changed

+155
-83
lines changed

lib/controllers/environment.py

Lines changed: 153 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
from typing import Union
2+
from datetime import datetime
23

4+
import logging
35
import jsonpickle
4-
from rocketpy.environment.environment import Environment
6+
from rocketpy.environment.environment import Environment as RocketPyEnvironment
57
from fastapi import HTTPException, status
68

9+
from lib.controllers import parse_error
710
from lib.models.environment import Env
811
from lib.repositories.environment import EnvRepository
912
from lib.views.environment import (
@@ -22,14 +25,28 @@ class EnvController:
2225
Controller for the Environment model.
2326
2427
Init Attributes:
25-
env (models.Env): Environment model object.
28+
env: models.Env
2629
2730
Enables:
28-
- Create a rocketpy.Environment object from an Env model object.
31+
- Simulation of RocketPyEnvironment from models.Env
32+
- CRUD operations over modeols.Env on the database
2933
"""
3034

3135
def __init__(self, env: Env):
32-
rocketpy_env = Environment(
36+
self._env = env
37+
38+
async def get_env(self) -> Env:
39+
return self._env
40+
41+
@staticmethod
42+
async def get_rocketpy_env(env: Env) -> RocketPyEnvironment:
43+
"""
44+
Get the rocketpy env object.
45+
46+
Returns:
47+
RocketPyEnvironment
48+
"""
49+
rocketpy_env = RocketPyEnvironment(
3350
latitude=env.latitude,
3451
longitude=env.longitude,
3552
elevation=env.elevation,
@@ -38,165 +55,220 @@ def __init__(self, env: Env):
3855
rocketpy_env.set_atmospheric_model(
3956
type=env.atmospheric_model_type, file=env.atmospheric_model_file
4057
)
41-
self.rocketpy_env = rocketpy_env
42-
self.env = env
58+
return rocketpy_env
4359

4460
async def create_env(self) -> "Union[EnvCreated, HTTPException]":
4561
"""
4662
Create a env in the database.
4763
4864
Returns:
49-
EnvCreated: Environment id.
65+
views.EnvCreated
5066
"""
51-
env = EnvRepository(environment=self.env)
52-
successfully_created_env = await env.create_env()
53-
if not successfully_created_env:
67+
env = self.get_env()
68+
env_repo = EnvRepository(environment=env)
69+
try:
70+
await env_repo.create_env()
71+
except Exception as e:
72+
exc_str = parse_error(e)
73+
logging.error(f"controllers/environment.create_env: {exc_str}")
5474
raise HTTPException(
5575
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
56-
detail="Failed to create environment",
76+
detail=f"Failed to create environment: {e}",
77+
) from e
78+
else:
79+
return EnvCreated(env_id=env_repo.get_env_id())
80+
finally:
81+
logging.info(
82+
f"[{datetime.now()}] Call to controllers/environment.create_env; params: Env {env.__hash__()}"
5783
)
5884

59-
return EnvCreated(env_id=str(env.env_id))
60-
6185
@staticmethod
62-
async def get_env(env_id: int) -> "Union[Env, HTTPException]":
86+
async def get_env_by_id(env_id: int) -> "Union[Env, HTTPException]":
6387
"""
6488
Get a env from the database.
6589
6690
Args:
67-
env_id (int): Environment id.
91+
env_id: int
6892
6993
Returns:
70-
env model object
94+
models.Env
7195
7296
Raises:
7397
HTTP 404 Not Found: If the env is not found in the database.
7498
"""
75-
successfully_read_env = await EnvRepository(env_id=env_id).get_env()
76-
if not successfully_read_env:
99+
env_repo = EnvRepository(env_id=env_id)
100+
try:
101+
read_env = await env_repo.get_env()
102+
except Exception as e:
103+
exc_str = parse_error(e)
104+
logging.error(f"controllers/environment.get_env_by_id: {exc_str}")
77105
raise HTTPException(
78-
status_code=status.HTTP_404_NOT_FOUND, detail="Environment not found"
106+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
107+
detail=f"Failed to read environment: {e}",
108+
) from e
109+
else:
110+
if read_env:
111+
return read_env
112+
raise HTTPException(
113+
status_code=status.HTTP_404_NOT_FOUND,
114+
detail="Environment not found",
115+
)
116+
finally:
117+
logging.info(
118+
f"[{datetime.now()}] Call to controllers/environment.get_env_by_id; params: EnvID {env_id}"
79119
)
80120

81-
return successfully_read_env
82-
83-
@staticmethod
84-
async def get_rocketpy_env(env_id: int) -> "Union[EnvPickle, HTTPException]":
121+
@classmethod
122+
async def get_rocketpy_env_as_jsonpickle(
123+
cls,
124+
env_id: int,
125+
) -> "Union[EnvPickle, HTTPException]":
85126
"""
86-
Get a rocketpy env object encoded as jsonpickle string from the database.
127+
Get rocketpy.Environmnet as jsonpickle string.
87128
88129
Args:
89-
env_id (int): env id.
130+
env_id: int
90131
91132
Returns:
92-
str: jsonpickle string of the rocketpy env.
133+
views.EnvPickle
93134
94135
Raises:
95136
HTTP 404 Not Found: If the env is not found in the database.
96137
"""
97-
successfully_read_env = await EnvRepository(env_id=env_id).get_env()
98-
if not successfully_read_env:
138+
env_repo = EnvRepository(env_id=env_id)
139+
try:
140+
read_env = await env_repo.get_env()
141+
except Exception as e:
142+
exc_str = parse_error(e)
143+
logging.error(
144+
f"controllers/environment.get_rocketpy_env_as_jsonpickle: {exc_str}"
145+
)
146+
raise HTTPException(
147+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
148+
detail=f"Failed to read environment: {e}",
149+
) from e
150+
else:
151+
if read_env:
152+
rocketpy_env = cls.get_rocketpy_env(read_env)
153+
return EnvPickle(
154+
jsonpickle_rocketpy_env=jsonpickle.encode(rocketpy_env)
155+
)
99156
raise HTTPException(
100-
status_code=status.HTTP_404_NOT_FOUND, detail="Environment not found"
157+
status_code=status.HTTP_404_NOT_FOUND,
158+
detail="Environment not found",
159+
)
160+
finally:
161+
logging.info(
162+
f"[{datetime.now()}] Call to controllers/environment.get_rocketpy_env_as_jsonpickle; params: EnvID {env_id}"
101163
)
102164

103-
successfully_read_rocketpy_env = EnvController(
104-
successfully_read_env
105-
).rocketpy_env
106-
107-
return EnvPickle(
108-
jsonpickle_rocketpy_env=jsonpickle.encode(successfully_read_rocketpy_env)
109-
)
110-
111-
async def update_env(self, env_id: int) -> "Union[EnvUpdated, HTTPException]":
165+
async def update_env(
166+
self, env_id: int
167+
) -> "Union[EnvUpdated, HTTPException]":
112168
"""
113169
Update a env in the database.
114170
115171
Args:
116-
env_id (int): env id.
172+
env_id: int
117173
118174
Returns:
119-
EnvUpdated: env id and message.
175+
views.EnvUpdated
120176
121177
Raises:
122178
HTTP 404 Not Found: If the env is not found in the database.
123179
"""
124-
successfully_read_env = await EnvRepository(env_id=env_id).get_env()
125-
if not successfully_read_env:
126-
raise HTTPException(
127-
status_code=status.HTTP_404_NOT_FOUND, detail="Environment not found"
128-
)
129-
130-
successfully_updated_env = await EnvRepository(
131-
environment=self.env, env_id=env_id
132-
).update_env()
133-
if not successfully_updated_env:
180+
env = self.get_env()
181+
env_repo = EnvRepository(environment=env, env_id=env_id)
182+
try:
183+
read_env = await env_repo.get_env()
184+
if read_env:
185+
await env_repo.update_env()
186+
else:
187+
raise HTTPException(
188+
status_code=status.HTTP_404_NOT_FOUND,
189+
detail="Environment not found",
190+
)
191+
except Exception as e:
192+
exc_str = parse_error(e)
193+
logging.error(f"controllers/environment.update_env: {exc_str}")
134194
raise HTTPException(
135195
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
136-
detail="Failed to update environment",
196+
detail=f"Failed to update environment: {e}",
197+
) from e
198+
else:
199+
return EnvUpdated(new_env_id=env_repo.get_env_id())
200+
finally:
201+
logging.info(
202+
f"[{datetime.now()}] Call to controllers/environment.update_env; params: EnvID {env_id}, Env {env.__hash__()}"
137203
)
138204

139-
return EnvUpdated(new_env_id=str(successfully_updated_env))
140-
141205
@staticmethod
142-
async def delete_env(env_id: int) -> "Union[EnvDeleted, HTTPException]":
206+
async def delete_env(env_id: str) -> "Union[EnvDeleted, HTTPException]":
143207
"""
144208
Delete a env from the database.
145209
146210
Args:
147-
env_id (int): Environment id.
211+
env_id: int
148212
149213
Returns:
150-
EnvDeleted: Environment id and message.
214+
views.EnvDeleted
151215
152216
Raises:
153217
HTTP 404 Not Found: If the env is not found in the database.
154218
"""
155-
successfully_read_env = await EnvRepository(env_id=env_id).get_env()
156-
if not successfully_read_env:
157-
raise HTTPException(
158-
status_code=status.HTTP_404_NOT_FOUND, detail="Environment not found"
159-
)
160-
161-
successfully_deleted_env = await EnvRepository(env_id=env_id).delete_env()
162-
if not successfully_deleted_env:
219+
env_repo = EnvRepository(env_id=env_id)
220+
try:
221+
await env_repo.delete_env()
222+
except Exception as e:
223+
exc_str = parse_error(e)
224+
logging.error(f"controllers/environment.delete_env: {exc_str}")
163225
raise HTTPException(
164226
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
165-
detail="Failed to delete environment",
227+
detail=f"Failed to delete environment: {e}",
228+
) from e
229+
else:
230+
return EnvDeleted(deleted_env_id=env_id)
231+
finally:
232+
logging.info(
233+
f"[{datetime.now()}] Call to controllers/environment.delete_env; params: EnvID {env_id}"
166234
)
167235

168-
return EnvDeleted(deleted_env_id=str(env_id))
169-
170-
@staticmethod
171-
async def simulate(env_id: int) -> "Union[EnvSummary, HTTPException]":
236+
@classmethod
237+
async def simulate(cls, env_id: int) -> "Union[EnvSummary, HTTPException]":
172238
"""
173239
Simulate a rocket environment.
174240
175241
Args:
176-
env_id (int): Env id.
242+
env_id: int.
177243
178244
Returns:
179-
Env summary view.
245+
views.EnvSummary
180246
181247
Raises:
182248
HTTP 404 Not Found: If the env does not exist in the database.
183249
"""
184-
successfully_read_env = await EnvRepository(env_id=env_id).get_env()
185-
if not successfully_read_env:
186-
raise HTTPException(
187-
status_code=status.HTTP_404_NOT_FOUND, detail="Environment not found"
188-
)
189-
250+
read_env = await cls.get_env_by_id(env_id)
190251
try:
191-
env = EnvController(successfully_read_env).rocketpy_env
192-
env_simulation_numbers = EnvData.parse_obj(env.all_info_returned())
193-
env_simulation_plots = EnvPlots.parse_obj(env.all_plot_info_returned())
252+
rocketpy_env = cls.get_rocketpy_env(read_env)
253+
env_simulation_numbers = EnvData.parse_obj(
254+
rocketpy_env.all_info_returned()
255+
)
256+
env_simulation_plots = EnvPlots.parse_obj(
257+
rocketpy_env.all_plot_info_returned()
258+
)
194259
env_summary = EnvSummary(
195260
env_data=env_simulation_numbers, env_plots=env_simulation_plots
196261
)
197-
return env_summary
198262
except Exception as e:
263+
exc_str = parse_error(e)
264+
logging.error(f"controllers/environment.simulate: {exc_str}")
199265
raise HTTPException(
200266
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
201267
detail=f"Failed to simulate environment: {e}",
202268
) from e
269+
else:
270+
return env_summary
271+
finally:
272+
logging.info(
273+
f"[{datetime.now()}] Call to controllers/environment.simulate; params: EnvID {env_id}"
274+
)

lib/models/environment.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,6 @@ class Env(BaseModel, frozen=True):
1111
# Opional parameters
1212
atmospheric_model_type: Optional[str] = "standard_atmosphere"
1313
atmospheric_model_file: Optional[str] = "GFS"
14-
date: Optional[datetime.datetime] = datetime.datetime.today() + datetime.timedelta(
15-
days=1
14+
date: Optional[datetime.datetime] = (
15+
datetime.datetime.today() + datetime.timedelta(days=1)
1616
)

0 commit comments

Comments
 (0)