|
2 | 2 | from fastapi import Response, Request, status, HTTPException
|
3 | 3 | from database.models.device_plant import DevicePlant
|
4 | 4 | from schemas.device_plant import (
|
| 5 | + DevicePlantCreateSchema, |
5 | 6 | DevicePlantPartialUpdateSchema,
|
6 |
| - DevicePlantSchema, |
7 | 7 | DevicePlantUpdateSchema,
|
8 | 8 | )
|
9 | 9 | import logging
|
10 |
| -from psycopg2.errors import UniqueViolation |
11 | 10 | from sqlalchemy.exc import PendingRollbackError, IntegrityError, NoResultFound
|
12 | 11 | from fastapi.responses import JSONResponse
|
| 12 | +from service.plant_service import PlantService |
13 | 13 |
|
14 | 14 | logger = logging.getLogger("app")
|
15 | 15 | logger.setLevel("DEBUG")
|
16 | 16 |
|
17 | 17 |
|
18 |
| -def withSQLExceptionsHandle(func): |
19 |
| - def handleSQLException(*args, **kwargs): |
20 |
| - try: |
21 |
| - return func(*args, **kwargs) |
22 |
| - except IntegrityError as err: |
23 |
| - if isinstance(err.orig, UniqueViolation): |
24 |
| - parsed_error = err.orig.pgerror.split("\n") |
25 |
| - raise HTTPException( |
26 |
| - status_code=status.HTTP_400_BAD_REQUEST, |
27 |
| - detail={"error": parsed_error[0], "detail": parsed_error[1]}, |
28 |
| - ) |
29 |
| - |
30 |
| - raise HTTPException( |
31 |
| - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=format(err) |
32 |
| - ) |
| 18 | +def handle_common_errors(err): |
33 | 19 |
|
34 |
| - except PendingRollbackError as err: |
35 |
| - logger.warning(format(err)) |
36 |
| - raise HTTPException( |
37 |
| - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=format(err) |
38 |
| - ) |
| 20 | + if isinstance(err, IntegrityError): |
| 21 | + parsed_error = err.orig.pgerror.split("\n")[1] |
| 22 | + return JSONResponse( |
| 23 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 24 | + content=parsed_error, |
| 25 | + ) |
39 | 26 |
|
40 |
| - except NoResultFound as err: |
41 |
| - raise HTTPException( |
42 |
| - status_code=status.HTTP_400_BAD_REQUEST, detail=format(err) |
43 |
| - ) |
| 27 | + if isinstance(err, PendingRollbackError): |
| 28 | + logger.warning(format(err)) |
| 29 | + raise HTTPException( |
| 30 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 31 | + detail=format(err) |
| 32 | + ) |
| 33 | + |
| 34 | + if isinstance(err, NoResultFound): |
| 35 | + raise HTTPException( |
| 36 | + status_code=status.HTTP_400_BAD_REQUEST, detail=format(err) |
| 37 | + ) |
| 38 | + |
| 39 | + logger.error(format(err)) |
| 40 | + raise HTTPException( |
| 41 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=format(err) |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | +def withSQLExceptionsHandle(async_mode: bool): |
| 46 | + |
| 47 | + def decorator(func): |
| 48 | + async def handleAsyncSQLException(*args, **kwargs): |
| 49 | + try: |
| 50 | + return await func(*args, **kwargs) |
| 51 | + except Exception as err: |
| 52 | + return handle_common_errors(err) |
| 53 | + |
| 54 | + def handleSyncSQLException(*args, **kwargs): |
| 55 | + try: |
| 56 | + return func(*args, **kwargs) |
| 57 | + except Exception as err: |
| 58 | + return handle_common_errors(err) |
44 | 59 |
|
45 |
| - return handleSQLException |
| 60 | + return ( |
| 61 | + handleAsyncSQLException if async_mode else handleSyncSQLException |
| 62 | + ) |
| 63 | + |
| 64 | + return decorator |
46 | 65 |
|
47 | 66 |
|
48 |
| -@withSQLExceptionsHandle |
49 |
| -def create_device_plant_relation(req: Request, device_plant: DevicePlantSchema): |
| 67 | +@withSQLExceptionsHandle(async_mode=True) |
| 68 | +async def create_device_plant_relation( |
| 69 | + req: Request, device_plant: DevicePlantCreateSchema |
| 70 | +): |
50 | 71 | try:
|
51 |
| - req.app.database.add(DevicePlant.from_pydantic(device_plant)) |
52 |
| - return req.app.database.find_by_device_id(device_plant.id_device) |
| 72 | + plant = await PlantService.get_plant(device_plant.id_plant) |
| 73 | + if not plant: |
| 74 | + return JSONResponse( |
| 75 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 76 | + content={ |
| 77 | + "plant_id": ( |
| 78 | + "Could not found any plant " |
| 79 | + f"with id {device_plant.id_plant}" |
| 80 | + ) |
| 81 | + }, |
| 82 | + ) |
| 83 | + |
| 84 | + plant_type = await PlantService.get_plant_type(plant.scientific_name) |
| 85 | + if not plant_type: |
| 86 | + return JSONResponse( |
| 87 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 88 | + content={ |
| 89 | + "scientific_name": ( |
| 90 | + "Could not found any plant type " |
| 91 | + f"with scientific name {plant.scientific_name}" |
| 92 | + ) |
| 93 | + }, |
| 94 | + ) |
| 95 | + |
| 96 | + device_plant = DevicePlant( |
| 97 | + id_device=device_plant.id_device, |
| 98 | + id_plant=device_plant.id_plant, |
| 99 | + plant_type=plant_type.id, |
| 100 | + id_user=plant.id_user, |
| 101 | + ) # type: ignore |
| 102 | + req.app.database.add(device_plant) |
| 103 | + return device_plant |
| 104 | + |
53 | 105 | except Exception as err:
|
54 | 106 | req.app.database.rollback()
|
55 | 107 | raise err
|
56 | 108 |
|
57 | 109 |
|
58 |
| -@withSQLExceptionsHandle |
59 |
| -def update_device_plant( |
| 110 | +@withSQLExceptionsHandle(async_mode=True) |
| 111 | +async def update_device_plant( |
60 | 112 | req: Request,
|
61 | 113 | id_device: str,
|
62 | 114 | device_plant_update_set: Union[
|
63 | 115 | DevicePlantUpdateSchema, DevicePlantPartialUpdateSchema
|
64 | 116 | ],
|
65 | 117 | ):
|
66 | 118 | try:
|
| 119 | + if not device_plant_update_set.id_plant: |
| 120 | + return req.app.database.find_by_device_id(id_device) |
| 121 | + |
| 122 | + plant = await PlantService.get_plant(device_plant_update_set.id_plant) |
| 123 | + if not plant: |
| 124 | + return JSONResponse( |
| 125 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 126 | + content={ |
| 127 | + "plant_id": ( |
| 128 | + "Could not found any plant with " |
| 129 | + f"id {device_plant_update_set.id_plant}" |
| 130 | + ) |
| 131 | + }, |
| 132 | + ) |
| 133 | + |
| 134 | + plant_type = await PlantService.get_plant_type(plant.scientific_name) |
| 135 | + if not plant_type: |
| 136 | + return JSONResponse( |
| 137 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 138 | + content={ |
| 139 | + "scientific_name": ( |
| 140 | + "Could not found any plant type " |
| 141 | + f"with scientific name {plant.scientific_name}" |
| 142 | + ) |
| 143 | + }, |
| 144 | + ) |
| 145 | + |
67 | 146 | req.app.database.update_device_plant(
|
68 | 147 | id_device,
|
69 |
| - device_plant_update_set.id_plant, |
70 |
| - device_plant_update_set.plant_type, |
71 |
| - device_plant_update_set.id_user, |
| 148 | + plant.id, |
| 149 | + plant_type.id, |
| 150 | + plant.id_user, |
72 | 151 | )
|
73 | 152 | return req.app.database.find_by_device_id(id_device)
|
74 | 153 | except Exception as err:
|
75 | 154 | req.app.database.rollback()
|
76 | 155 | raise err
|
77 | 156 |
|
78 | 157 |
|
79 |
| -@withSQLExceptionsHandle |
80 |
| -def get_device_plant_relation(req: Request, id_plant: str): |
| 158 | +@withSQLExceptionsHandle(async_mode=False) |
| 159 | +def get_device_plant_relation(req: Request, id_plant: int): |
81 | 160 | return req.app.database.find_by_plant_id(id_plant)
|
82 | 161 |
|
83 | 162 |
|
84 |
| -@withSQLExceptionsHandle |
| 163 | +@withSQLExceptionsHandle(async_mode=False) |
85 | 164 | def get_all_device_plant_relations(req: Request, limit: int):
|
86 | 165 | return req.app.database.find_all(limit)
|
87 | 166 |
|
88 | 167 |
|
89 |
| -@withSQLExceptionsHandle |
| 168 | +@withSQLExceptionsHandle(async_mode=False) |
90 | 169 | def delete_device_plant_relation(
|
91 |
| - req: Request, response: Response, type_id: Literal["id_device", "id_plant"], id: str |
| 170 | + req: Request, |
| 171 | + response: Response, |
| 172 | + type_id: Literal["id_device", "id_plant"], |
| 173 | + id: str |
92 | 174 | ):
|
93 | 175 | result_rowcount = 0
|
94 | 176 | if type_id == "id_device":
|
|
0 commit comments