Skip to content

Commit 0e84a75

Browse files
committed
chore: reformat codebase with Black
1 parent f44dbb2 commit 0e84a75

File tree

11 files changed

+188
-117
lines changed

11 files changed

+188
-117
lines changed

.flake8

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ max-complexity = 10
44
select = E,F,W
55
extend-ignore = E203, W503
66
exclude = .venv
7+
per-file-ignores = tests/test_main.py: E501
78
count = True
89
show-source = True
910
statistics = True

databases/player_database.py

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
99
The `STORAGE_PATH` environment variable controls the SQLite file location.
1010
"""
11+
1112
import logging
1213
import os
1314
from typing import AsyncGenerator
@@ -21,16 +22,11 @@
2122
logging.getLogger("sqlalchemy.engine.Engine").handlers = logger.handlers
2223

2324
async_engine = create_async_engine(
24-
DATABASE_URL,
25-
connect_args={"check_same_thread": False},
26-
echo=True
25+
DATABASE_URL, connect_args={"check_same_thread": False}, echo=True
2726
)
2827

2928
async_sessionmaker = sessionmaker(
30-
bind=async_engine,
31-
class_=AsyncSession,
32-
autocommit=False,
33-
autoflush=False
29+
bind=async_engine, class_=AsyncSession, autocommit=False, autoflush=False
3430
)
3531

3632
Base = declarative_base()

main.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
88
This serves as the entry point for running the API server.
99
"""
10+
1011
from contextlib import asynccontextmanager
1112
import logging
1213
from typing import AsyncIterator
@@ -17,6 +18,7 @@
1718
UVICORN_LOGGER = "uvicorn.error"
1819
logger = logging.getLogger(UVICORN_LOGGER)
1920

21+
2022
@asynccontextmanager
2123
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
2224
"""
@@ -25,10 +27,13 @@ async def lifespan(_: FastAPI) -> AsyncIterator[None]:
2527
logger.info("Lifespan event handler execution complete.")
2628
yield
2729

28-
app = FastAPI(lifespan=lifespan,
29-
title="python-samples-fastapi-restful",
30-
description="🧪 Proof of Concept for a RESTful API made with Python 3 and FastAPI",
31-
version="1.0.0",)
30+
31+
app = FastAPI(
32+
lifespan=lifespan,
33+
title="python-samples-fastapi-restful",
34+
description="🧪 Proof of Concept for a RESTful API made with Python 3 and FastAPI",
35+
version="1.0.0",
36+
)
3237

3338
app.include_router(player_route.api_router)
3439
app.include_router(health_route.api_router)

models/player_model.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
77
These models are used for data validation and serialization in the API.
88
"""
9+
910
from typing import Optional
1011
from pydantic import BaseModel, ConfigDict
1112
from pydantic.alias_generators import to_camel
@@ -24,6 +25,7 @@ class MainModel(BaseModel):
2425
Here, it uses `to_camel` to convert field names to camelCase.
2526
populate_by_name (bool): Allows population of fields by name when using Pydantic models.
2627
"""
28+
2729
model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)
2830

2931

@@ -44,6 +46,7 @@ class PlayerModel(MainModel):
4446
league (Optional[str]): The league where the team plays, if any.
4547
starting11 (Optional[bool]): Indicates if the Player is in the starting 11, if provided.
4648
"""
49+
4750
id: int
4851
first_name: str
4952
middle_name: Optional[str]

pyproject.toml

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,16 @@ include = '\.pyi?$'
55
exclude = '''
66
/(
77
\.git
8+
| \.github
9+
| \.pytest_cache
810
| \.venv
9-
| build
10-
| dist
11+
| \.vscode
12+
| assets
13+
| htmlcov
14+
| postman_collections
15+
| scripts
16+
| storage
1117
| __pycache__
12-
| \.eggs
13-
| \.mypy_cache
14-
| \.tox
18+
| tests/test_main\.py
1519
)/
1620
'''

routes/health_route.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
Defines a simple endpoint to verify that the service is up and running.
55
Returns a JSON response with a "status" key set to "ok".
66
"""
7+
78
from fastapi import APIRouter
89

910
api_router = APIRouter()
1011

12+
1113
@api_router.get("/health", tags=["Health"])
1214
async def health_check():
1315
"""

routes/player_route.py

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
- PUT /players/{player_id} : Update an existing Player.
1717
- DELETE /players/{player_id} : Delete an existing Player.
1818
"""
19+
1920
from typing import List
2021
from fastapi import APIRouter, Body, Depends, HTTPException, status, Path, Response
2122
from sqlalchemy.ext.asyncio import AsyncSession
@@ -29,7 +30,7 @@
2930
simple_memory_cache = SimpleMemoryCache()
3031

3132
CACHE_KEY = "players"
32-
CACHE_TTL = 600 # 10 minutes
33+
CACHE_TTL = 600 # 10 minutes
3334

3435
# POST -------------------------------------------------------------------------
3536

@@ -38,11 +39,11 @@
3839
"/players/",
3940
status_code=status.HTTP_201_CREATED,
4041
summary="Creates a new Player",
41-
tags=["Players"]
42+
tags=["Players"],
4243
)
4344
async def post_async(
4445
player_model: PlayerModel = Body(...),
45-
async_session: AsyncSession = Depends(generate_async_session)
46+
async_session: AsyncSession = Depends(generate_async_session),
4647
):
4748
"""
4849
Endpoint to create a new player.
@@ -60,6 +61,7 @@ async def post_async(
6061
await player_service.create_async(async_session, player_model)
6162
await simple_memory_cache.clear(CACHE_KEY)
6263

64+
6365
# GET --------------------------------------------------------------------------
6466

6567

@@ -68,11 +70,10 @@ async def post_async(
6870
response_model=List[PlayerModel],
6971
status_code=status.HTTP_200_OK,
7072
summary="Retrieves a collection of Players",
71-
tags=["Players"]
73+
tags=["Players"],
7274
)
7375
async def get_all_async(
74-
response: Response,
75-
async_session: AsyncSession = Depends(generate_async_session)
76+
response: Response, async_session: AsyncSession = Depends(generate_async_session)
7677
):
7778
"""
7879
Endpoint to retrieve all players.
@@ -97,11 +98,11 @@ async def get_all_async(
9798
response_model=PlayerModel,
9899
status_code=status.HTTP_200_OK,
99100
summary="Retrieves a Player by its Id",
100-
tags=["Players"]
101+
tags=["Players"],
101102
)
102103
async def get_by_id_async(
103104
player_id: int = Path(..., title="The ID of the Player"),
104-
async_session: AsyncSession = Depends(generate_async_session)
105+
async_session: AsyncSession = Depends(generate_async_session),
105106
):
106107
"""
107108
Endpoint to retrieve a Player by its ID.
@@ -127,11 +128,11 @@ async def get_by_id_async(
127128
response_model=PlayerModel,
128129
status_code=status.HTTP_200_OK,
129130
summary="Retrieves a Player by its Squad Number",
130-
tags=["Players"]
131+
tags=["Players"],
131132
)
132133
async def get_by_squad_number_async(
133134
squad_number: int = Path(..., title="The Squad Number of the Player"),
134-
async_session: AsyncSession = Depends(generate_async_session)
135+
async_session: AsyncSession = Depends(generate_async_session),
135136
):
136137
"""
137138
Endpoint to retrieve a Player by its Squad Number.
@@ -146,24 +147,27 @@ async def get_by_squad_number_async(
146147
Raises:
147148
HTTPException: HTTP 404 Not Found error if the Player with the specified Squad Number does not exist.
148149
"""
149-
player = await player_service.retrieve_by_squad_number_async(async_session, squad_number)
150+
player = await player_service.retrieve_by_squad_number_async(
151+
async_session, squad_number
152+
)
150153
if not player:
151154
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND)
152155
return player
153156

157+
154158
# PUT --------------------------------------------------------------------------
155159

156160

157161
@api_router.put(
158162
"/players/{player_id}",
159163
status_code=status.HTTP_204_NO_CONTENT,
160164
summary="Updates an existing Player",
161-
tags=["Players"]
165+
tags=["Players"],
162166
)
163167
async def put_async(
164168
player_id: int = Path(..., title="The ID of the Player"),
165169
player_model: PlayerModel = Body(...),
166-
async_session: AsyncSession = Depends(generate_async_session)
170+
async_session: AsyncSession = Depends(generate_async_session),
167171
):
168172
"""
169173
Endpoint to entirely update an existing Player.
@@ -182,18 +186,19 @@ async def put_async(
182186
await player_service.update_async(async_session, player_model)
183187
await simple_memory_cache.clear(CACHE_KEY)
184188

189+
185190
# DELETE -----------------------------------------------------------------------
186191

187192

188193
@api_router.delete(
189194
"/players/{player_id}",
190195
status_code=status.HTTP_204_NO_CONTENT,
191196
summary="Deletes an existing Player",
192-
tags=["Players"]
197+
tags=["Players"],
193198
)
194199
async def delete_async(
195200
player_id: int = Path(..., title="The ID of the Player"),
196-
async_session: AsyncSession = Depends(generate_async_session)
201+
async_session: AsyncSession = Depends(generate_async_session),
197202
):
198203
"""
199204
Endpoint to delete an existing Player.

schemas/player_schema.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
66
Used for async database CRUD operations in the application.
77
"""
8+
89
from sqlalchemy import Column, String, Integer, Boolean
910
from databases.player_database import Base
1011

@@ -30,13 +31,13 @@ class Player(Base):
3031
__tablename__ = "players"
3132

3233
id = Column(Integer, primary_key=True)
33-
first_name = Column(String, name='firstName', nullable=False)
34-
middle_name = Column(String, name='middleName')
35-
last_name = Column(String, name='lastName', nullable=False)
34+
first_name = Column(String, name="firstName", nullable=False)
35+
middle_name = Column(String, name="middleName")
36+
last_name = Column(String, name="lastName", nullable=False)
3637
date_of_birth = Column(String, name="dateOfBirth")
37-
squad_number = Column(Integer, name='squadNumber', unique=True, nullable=False)
38+
squad_number = Column(Integer, name="squadNumber", unique=True, nullable=False)
3839
position = Column(String, nullable=False)
39-
abbr_position = Column(String, name='abbrPosition')
40+
abbr_position = Column(String, name="abbrPosition")
4041
team = Column(String)
4142
league = Column(String)
4243
starting11 = Column(Boolean)

services/player_service.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
1212
Handles SQLAlchemy exceptions with transaction rollback and logs errors.
1313
"""
14+
1415
from sqlalchemy import select
1516
from sqlalchemy.ext.asyncio import AsyncSession
1617
from sqlalchemy.exc import SQLAlchemyError
@@ -42,6 +43,7 @@ async def create_async(async_session: AsyncSession, player_model: PlayerModel):
4243
await async_session.rollback()
4344
return False
4445

46+
4547
# Retrieve ---------------------------------------------------------------------
4648

4749

@@ -77,7 +79,9 @@ async def retrieve_by_id_async(async_session: AsyncSession, player_id: int):
7779
return player
7880

7981

80-
async def retrieve_by_squad_number_async(async_session: AsyncSession, squad_number: int):
82+
async def retrieve_by_squad_number_async(
83+
async_session: AsyncSession, squad_number: int
84+
):
8185
"""
8286
Retrieves a Player by its Squad Number from the database.
8387
@@ -93,6 +97,7 @@ async def retrieve_by_squad_number_async(async_session: AsyncSession, squad_numb
9397
player = result.scalars().first()
9498
return player
9599

100+
96101
# Update -----------------------------------------------------------------------
97102

98103

@@ -127,6 +132,7 @@ async def update_async(async_session: AsyncSession, player_model: PlayerModel):
127132
await async_session.rollback()
128133
return False
129134

135+
130136
# Delete -----------------------------------------------------------------------
131137

132138

tests/player_stub.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __init__(
1515
abbr_position=None,
1616
team=None,
1717
league=None,
18-
starting11=None
18+
starting11=None,
1919
):
2020
self.id = id
2121
self.first_name = first_name
@@ -77,5 +77,5 @@ def unknown_player():
7777
first_name="John",
7878
last_name="Doe",
7979
squad_number="999",
80-
position="Lipsum"
80+
position="Lipsum",
8181
)

0 commit comments

Comments
 (0)