forked from nanotaboada/python-samples-fastapi-restful
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.py
More file actions
225 lines (184 loc) · 7.06 KB
/
player.py
File metadata and controls
225 lines (184 loc) · 7.06 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
"""
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 ID.
- GET /players/squadnumber/{squad_number} : Retrieve Player by Squad Number.
- PUT /players/{player_id} : Update an existing Player.
- DELETE /players/{player_id} : Delete an existing Player.
"""
from typing import List
from fastapi import APIRouter, Body, Depends, HTTPException, status, Path, Response
from sqlalchemy.ext.asyncio import AsyncSession
from aiocache import SimpleMemoryCache
from src.databases.player import generate_async_session
from src.models.player import PlayerModel
from src.services import player
router = APIRouter()
simple_memory_cache = SimpleMemoryCache()
CACHE_KEY = "players"
CACHE_TTL = 600 # 10 minutes
PLAYER_TITLE = "The ID of the Player"
# POST -------------------------------------------------------------------------
@router.post(
"/players/",
status_code=status.HTTP_201_CREATED,
summary="Creates a new Player",
tags=["Players"],
)
async def post_async(
player_model: PlayerModel = Body(...),
async_session: AsyncSession = Depends(generate_async_session),
):
"""
Endpoint to create a new player.
Args:
player_model (PlayerModel): The Pydantic model representing the Player to
create.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Raises:
HTTPException: HTTP 409 Conflict error if the Player already exists.
"""
player_res = await player.retrieve_by_id_async(async_session, player_model.id)
if player_res:
raise HTTPException(status_code=status.HTTP_409_CONFLICT)
await player.create_async(async_session, player_model)
await simple_memory_cache.clear(CACHE_KEY)
# GET --------------------------------------------------------------------------
@router.get(
"/players/",
response_model=List[PlayerModel],
status_code=status.HTTP_200_OK,
summary="Retrieves a collection of Players",
tags=["Players"],
)
async def get_all_async(
response: Response, async_session: AsyncSession = Depends(generate_async_session)
):
"""
Endpoint to retrieve all players.
Args:
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
List[PlayerModel]: 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.retrieve_all_async(async_session)
await simple_memory_cache.set(CACHE_KEY, players, ttl=CACHE_TTL)
response.headers["X-Cache"] = "MISS"
return players
@router.get(
"/players/{player_id}",
response_model=PlayerModel,
status_code=status.HTTP_200_OK,
summary="Retrieves a Player by its Id",
tags=["Players"],
)
async def get_by_id_async(
player_id: int = Path(..., title=PLAYER_TITLE),
async_session: AsyncSession = Depends(generate_async_session),
):
"""
Endpoint to retrieve a Player by its ID.
Args:
player_id (int): The ID of the Player to retrieve.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Returns:
PlayerModel: The Pydantic model representing the matching Player.
Raises:
HTTPException: Not found error if the Player with the specified ID does not
exist.
"""
player_res = await player.retrieve_by_id_async(async_session, player_id)
if not player_res:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return player_res
@router.get(
"/players/squadnumber/{squad_number}",
response_model=PlayerModel,
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: int = Path(..., title="The Squad Number of the Player"),
async_session: 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:
PlayerModel: 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_res = await player.retrieve_by_squad_number_async(
async_session, squad_number
)
if not player_res:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
return player_res
# PUT --------------------------------------------------------------------------
@router.put(
"/players/{player_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Updates an existing Player",
tags=["Players"],
)
async def put_async(
player_id: int = Path(..., title=PLAYER_TITLE),
player_model: PlayerModel = Body(...),
async_session: AsyncSession = Depends(generate_async_session),
):
"""
Endpoint to entirely update an existing Player.
Args:
player_id (int): The ID of the Player to update.
player_model (PlayerModel): The Pydantic model representing the Player to
update.
async_session (AsyncSession): The async version of a SQLAlchemy ORM session.
Raises:
HTTPException: HTTP 404 Not Found error if the Player with the specified ID
does not exist.
"""
player_res = await player.retrieve_by_id_async(async_session, player_id)
if not player_res:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
await player.update_async(async_session, player_model)
await simple_memory_cache.clear(CACHE_KEY)
# DELETE -----------------------------------------------------------------------
@router.delete(
"/players/{player_id}",
status_code=status.HTTP_204_NO_CONTENT,
summary="Deletes an existing Player",
tags=["Players"],
)
async def delete_async(
player_id: int = Path(..., title=PLAYER_TITLE),
async_session: AsyncSession = Depends(generate_async_session),
):
"""
Endpoint to delete an existing Player.
Args:
player_id (int): The ID 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 ID
does not exist.
"""
player_res = await player.retrieve_by_id_async(async_session, player_id)
if not player_res:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
await player.delete_async(async_session, player_id)
await simple_memory_cache.clear(CACHE_KEY)