-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathplayer_route.py
More file actions
263 lines (222 loc) · 8.95 KB
/
player_route.py
File metadata and controls
263 lines (222 loc) · 8.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""
API routes for managing Player resources.
Provides CRUD endpoints to create, read, update, and delete Player entities.
Features:
- Caching with in-memory cache to optimize retrieval performance.
- Async database session dependency injection.
- Standard HTTP status codes and error handling.
Endpoints:
- POST /players/ : Create a new Player.
- GET /players/ : Retrieve all Players.
- GET /players/{player_id} : Retrieve Player by UUID
(surrogate key, internal).
- GET /players/squadnumber/{squad_number} : Retrieve Player by Squad Number
(natural key, domain).
- PUT /players/squadnumber/{squad_number} : Update an existing Player.
- DELETE /players/squadnumber/{squad_number} : Delete an existing Player.
"""
from typing import Annotated, List
from uuid import UUID
from fastapi import APIRouter, Body, Depends, HTTPException, status, Path, Response
from sqlalchemy.ext.asyncio import AsyncSession
from aiocache import SimpleMemoryCache
from databases.player_database import generate_async_session
from models.player_model import PlayerRequestModel, PlayerResponseModel
from services import player_service
api_router = APIRouter()
simple_memory_cache = SimpleMemoryCache()
CACHE_KEY = "players"
CACHE_TTL = 600 # 10 minutes
SQUAD_NUMBER_TITLE = "The Squad Number of the Player"
# POST -------------------------------------------------------------------------
@api_router.post(
"/players/",
response_model=PlayerResponseModel,
status_code=status.HTTP_201_CREATED,
summary="Creates a new Player",
tags=["Players"],
)
async def post_async(
player_model: Annotated[PlayerRequestModel, Body(...)],
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to create a new player.
Args:
player_model (PlayerRequestModel): The Pydantic model representing the Player
to create.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
PlayerResponseModel: The created Player with its generated UUID.
Raises:
HTTPException: HTTP 409 Conflict error if the Player already exists.
"""
existing = await player_service.retrieve_by_squad_number_async(
async_session, player_model.squad_number
)
if existing:
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
player = await player_service.create_async(async_session, player_model)
if player is None: # pragma: no cover
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to create the Player due to a database error.",
)
await simple_memory_cache.clear(CACHE_KEY)
return player
# GET --------------------------------------------------------------------------
@api_router.get(
"/players/",
response_model=List[PlayerResponseModel],
status_code=status.HTTP_200_OK,
summary="Retrieves a collection of Players",
tags=["Players"],
)
async def get_all_async(
response: Response,
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to retrieve all players.
Args:
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
List[PlayerResponseModel]: A list of Pydantic models representing all players.
"""
players = await simple_memory_cache.get(CACHE_KEY)
response.headers["X-Cache"] = "HIT"
if not players:
players = await player_service.retrieve_all_async(async_session)
await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
response.headers["X-Cache"] = "MISS"
return players
@api_router.get(
"/players/{player_id}",
response_model=PlayerResponseModel,
status_code=status.HTTP_200_OK,
summary="Retrieves a Player by its UUID",
tags=["Players"],
)
async def get_by_id_async(
player_id: Annotated[UUID, Path(..., title="The UUID of the Player")],
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to retrieve a Player by its UUID.
Args:
player_id (UUID): The UUID of the Player to retrieve.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
PlayerResponseModel: The Pydantic model representing the matching Player.
Raises:
HTTPException: Not found error if the Player with the specified UUID does not
exist.
"""
player = await player_service.retrieve_by_id_async(async_session, player_id)
if not player:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return player
@api_router.get(
"/players/squadnumber/{squad_number}",
response_model=PlayerResponseModel,
status_code=status.HTTP_200_OK,
summary="Retrieves a Player by its Squad Number",
tags=["Players"],
)
async def get_by_squad_number_async(
squad_number: Annotated[int, Path(..., title=SQUAD_NUMBER_TITLE)],
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to retrieve a Player by its Squad Number.
Args:
squad_number (int): The Squad Number of the Player to retrieve.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
PlayerResponseModel: The Pydantic model representing the matching Player.
Raises:
HTTPException: HTTP 404 Not Found error if the Player with the specified
Squad Number does not exist.
"""
player = await player_service.retrieve_by_squad_number_async(
async_session, squad_number
)
if not player:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return player
# PUT --------------------------------------------------------------------------
@api_router.put(
"/players/squadnumber/{squad_number}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Updates an existing Player",
tags=["Players"],
)
async def put_async(
squad_number: Annotated[int, Path(..., title=SQUAD_NUMBER_TITLE)],
player_model: Annotated[PlayerRequestModel, Body(...)],
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to entirely update an existing Player.
Args:
squad_number (int): The Squad Number of the Player to update.
player_model (PlayerRequestModel): The Pydantic model representing the Player
to update.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Raises:
HTTPException: HTTP 400 Bad Request if squad_number in the request body does
not match the path parameter. The path parameter is the authoritative source
of identity on PUT; a mismatch makes the request ambiguous.
HTTPException: HTTP 404 Not Found error if the Player with the specified Squad
Number does not exist.
"""
if player_model.squad_number != squad_number:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
player = await player_service.retrieve_by_squad_number_async(
async_session, squad_number
)
if not player:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
updated = await player_service.update_by_squad_number_async(
async_session, squad_number, player_model
)
if not updated: # pragma: no cover
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to update the Player due to a database error.",
)
await simple_memory_cache.clear(CACHE_KEY)
# DELETE -----------------------------------------------------------------------
@api_router.delete(
"/players/squadnumber/{squad_number}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Deletes an existing Player",
tags=["Players"],
)
async def delete_async(
squad_number: Annotated[int, Path(..., title=SQUAD_NUMBER_TITLE)],
async_session: Annotated[AsyncSession, Depends(generate_async_session)],
):
"""
Endpoint to delete an existing Player.
Args:
squad_number (int): The Squad Number of the Player to delete.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Raises:
HTTPException: HTTP 404 Not Found error if the Player with the specified Squad
Number does not exist.
"""
player = await player_service.retrieve_by_squad_number_async(
async_session, squad_number
)
if not player:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
deleted = await player_service.delete_by_squad_number_async(
async_session, squad_number
)
if not deleted: # pragma: no cover
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to delete the Player due to a database error.",
)
await simple_memory_cache.clear(CACHE_KEY)