|
18 | 18 |
|
19 | 19 | from typing import Annotated, cast
|
20 | 20 |
|
21 |
| -from fastapi import Depends, HTTPException, Query, status |
| 21 | +from fastapi import Depends, HTTPException, Query, Response, status |
22 | 22 | from fastapi.exceptions import RequestValidationError
|
23 | 23 | from pydantic import ValidationError
|
24 | 24 | from sqlalchemy import delete, select
|
@@ -176,21 +176,49 @@ def post_pool(
|
176 | 176 | return pool
|
177 | 177 |
|
178 | 178 |
|
179 |
| -@pools_router.post( |
| 179 | +@pools_router.put( |
180 | 180 | "/bulk",
|
181 | 181 | status_code=status.HTTP_201_CREATED,
|
182 |
| - responses=create_openapi_http_exception_doc( |
183 |
| - [ |
184 |
| - status.HTTP_409_CONFLICT, # handled by global exception handler |
185 |
| - ] |
186 |
| - ), |
| 182 | + responses={ |
| 183 | + **create_openapi_http_exception_doc( |
| 184 | + [ |
| 185 | + status.HTTP_409_CONFLICT, # handled by global exception handler |
| 186 | + ] |
| 187 | + ), |
| 188 | + status.HTTP_201_CREATED: { |
| 189 | + "description": "Created", |
| 190 | + "model": PoolCollectionResponse, |
| 191 | + }, |
| 192 | + status.HTTP_200_OK: { |
| 193 | + "description": "Created with overwriting", |
| 194 | + "model": PoolCollectionResponse, |
| 195 | + }, |
| 196 | + }, |
187 | 197 | )
|
188 |
| -def post_pools( |
189 |
| - body: PoolPostBulkBody, |
| 198 | +def put_pools( |
| 199 | + response: Response, |
| 200 | + put_body: PoolPostBulkBody, |
190 | 201 | session: SessionDep,
|
191 | 202 | ) -> PoolCollectionResponse:
|
192 | 203 | """Create multiple pools."""
|
193 |
| - pools = [Pool(**body.model_dump()) for body in body.pools] |
| 204 | + response.status_code = status.HTTP_201_CREATED if not put_body.overwrite else status.HTTP_200_OK |
| 205 | + pools: list[Pool] |
| 206 | + if not put_body.overwrite: |
| 207 | + pools = [Pool(**body.model_dump()) for body in put_body.pools] |
| 208 | + else: |
| 209 | + pool_names = [pool.pool for pool in put_body.pools] |
| 210 | + existed_pools = session.execute(select(Pool).filter(Pool.pool.in_(pool_names))).scalars() |
| 211 | + existed_pools_dict = {pool.pool: pool for pool in existed_pools} |
| 212 | + pools = [] |
| 213 | + # if pool already exists, update the corresponding pool, else add a new pool |
| 214 | + for body in put_body.pools: |
| 215 | + if body.pool in existed_pools_dict: |
| 216 | + pool = existed_pools_dict[body.pool] |
| 217 | + for key, val in body.model_dump().items(): |
| 218 | + setattr(pool, key, val) |
| 219 | + pools.append(pool) |
| 220 | + else: |
| 221 | + pools.append(Pool(**body.model_dump())) |
194 | 222 | session.add_all(pools)
|
195 | 223 | return PoolCollectionResponse(
|
196 | 224 | pools=cast(list[PoolResponse], pools),
|
|
0 commit comments