Skip to content

Commit 20ad3aa

Browse files
committed
add descriptions for tags;comments on classes
1 parent dbf840d commit 20ad3aa

9 files changed

Lines changed: 157 additions & 90 deletions

File tree

globals.py

Lines changed: 54 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,44 @@
2828
password=config["REDIS"]["PASSWORD"],
2929
)
3030

31+
tags_metadata = [
32+
{
33+
"name": "ck_bonus",
34+
"description": "All queries concerning this table from `queries.sp`",
35+
},
36+
{
37+
"name": "ck_checkpoints",
38+
"description": "All queries concerning this table from `queries.sp`",
39+
},
40+
{
41+
"name": "ck_latestrecords",
42+
"description": "All queries concerning this table from `queries.sp`",
43+
},
44+
{
45+
"name": "ck_maptier",
46+
"description": "All queries concerning this table from `queries.sp`",
47+
},
48+
{
49+
"name": "ck_playeroptions2",
50+
"description": "All queries concerning this table from `queries.sp`",
51+
},
52+
{
53+
"name": "ck_playerrank",
54+
"description": "All queries concerning this table from `queries.sp`",
55+
},
56+
{
57+
"name": "ck_playertemp",
58+
"description": "All queries concerning this table from `queries.sp`",
59+
},
60+
{
61+
"name": "strays",
62+
"description": "All queries that were NOT contained in `queries.sp` for each table",
63+
},
64+
{
65+
"name": "Point Calculation",
66+
"description": "Queries that are involved in **player points** calculation",
67+
},
68+
]
3169

3270
# Whitelisted IPs
3371
WHITELISTED_IPS = config["WHITELISTED_IPS"]
@@ -73,7 +111,14 @@ def set_cache(cache_key: str, data):
73111

74112
redis_client.set(
75113
cache_key,
76-
json.dumps(data, use_decimal=True, encoding='utf-8', ensure_ascii=False, default=default_serializer, allow_nan=True),
114+
json.dumps(
115+
data,
116+
use_decimal=True,
117+
encoding="utf-8",
118+
ensure_ascii=False,
119+
default=default_serializer,
120+
allow_nan=True,
121+
),
77122
ex=config["REDIS"]["EXPIRY"],
78123
)
79124

@@ -94,19 +139,22 @@ def get_cache(cache_key: str):
94139
else:
95140
return None
96141

142+
97143
def ordinal(n):
98-
suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)]
144+
suffix = ["th", "st", "nd", "rd", "th"][min(n % 10, 4)]
99145
if 11 <= (n % 100) <= 13:
100-
suffix = 'th'
146+
suffix = "th"
101147
return str(n) + suffix
102148

149+
103150
def custom_date_format(dt):
104151
day = ordinal(dt.day)
105-
month = dt.strftime('%B')
152+
month = dt.strftime("%B")
106153
year = dt.year
107-
time = dt.strftime('%H:%M:%S')
154+
time = dt.strftime("%H:%M:%S")
108155
return f"{day} of {month} {year}, {time}"
109156

157+
110158
def custom_time_format(time_value):
111159
# Convert to Decimal for precise arithmetic
112160
time_value = Decimal(time_value)
@@ -120,6 +168,7 @@ def custom_time_format(time_value):
120168

121169
return formatted_time
122170

171+
123172
def default_serializer(obj):
124173
if isinstance(obj, datetime):
125174
return custom_date_format(obj)

main.py

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
token_auth_scheme,
1818
config,
1919
redis_client,
20+
tags_metadata,
2021
WHITELISTED_IPS,
2122
append_request_log,
2223
append_denied_log,
@@ -34,18 +35,6 @@
3435
from surftimer.ck_playertemp import router as ck_playertemp_router
3536

3637

37-
# Responses
38-
class ResponseInsertQuery:
39-
"""This is to be used for all `INSERT` queries if possible"""
40-
41-
def __init__(self, inserted):
42-
self.inserted = inserted
43-
44-
def to_dict(self):
45-
"""Makes it readable for `print()`"""
46-
return {"inserted": self.inserted}
47-
48-
4938
class IPValidatorMiddleware(BaseHTTPMiddleware):
5039
async def dispatch(self, request: Request, call_next):
5140
# Get client IP
@@ -85,6 +74,7 @@ async def dispatch(self, request: Request, call_next):
8574
debug=True,
8675
swagger_ui_parameters=swagger_config,
8776
middleware=[Middleware(IPValidatorMiddleware)],
77+
openapi_tags=tags_metadata,
8878
)
8979

9080

@@ -109,7 +99,7 @@ async def custom_swagger_ui_html_cdn():
10999
)
110100

111101

112-
@app.get("/")
102+
@app.get("/", include_in_schema=False)
113103
async def home():
114104
data = {"message": "Suuuuh duuuud"}
115105
return JSONResponse(status_code=status.HTTP_200_OK, content=data)

surftimer/ck_bonus.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313

1414
class NewBonus(BaseModel):
15+
"""Body for adding a new **Bonus** time"""
16+
1517
steamid32: str
1618
name: str
1719
mapname: str
@@ -22,14 +24,6 @@ class NewBonus(BaseModel):
2224
velStartZ: int
2325

2426

25-
class PlayerRankBonus(BaseModel):
26-
"""To be used for `selectPlayerRankBonus` endpoint"""
27-
28-
steamid32: str
29-
mapname: str
30-
zonegroup: int
31-
32-
3327
router = APIRouter()
3428

3529

surftimer/ck_checkpoints.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99

1010

1111
class PlayerCheckpoints(BaseModel):
12+
"""Body for adding or updating **Checkpoint** time"""
13+
1214
steamid: str
1315
mapname: str
1416
cp: int
@@ -48,18 +50,18 @@ async def insertOrUpdateCheckpoints(
4850
)
4951
xquery = insertQuery(sql)
5052
content_data = {"inserted": xquery, "xtime": time.perf_counter() - tic}
51-
53+
5254
if xquery < 1:
5355
# response.body = json.dumps(content_data).encode('utf-8')
54-
response.headers['content-type'] = 'application/json'
56+
response.headers["content-type"] = "application/json"
5557
response.status_code = status.HTTP_304_NOT_MODIFIED
5658
return response
5759

5860
# Prepare the response
5961
toc = time.perf_counter()
6062
print(f"Execution time {toc - tic:0.4f}")
61-
62-
response.body = json.dumps(content_data).encode('utf-8')
63+
64+
response.body = json.dumps(content_data).encode("utf-8")
6365
response.status_code = status.HTTP_201_CREATED
6466
return response
6567

@@ -81,7 +83,8 @@ async def selectCheckpoints(
8183
if cached_data is not None:
8284
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
8385
return JSONResponse(
84-
status_code=status.HTTP_200_OK, content=json.loads(cached_data, use_decimal=True, parse_nan=True)
86+
status_code=status.HTTP_200_OK,
87+
content=json.loads(cached_data, use_decimal=True, parse_nan=True),
8588
)
8689

8790
xquery = selectQuery(
@@ -126,7 +129,8 @@ async def selectCheckpointsinZoneGroup(
126129
if cached_data is not None:
127130
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
128131
return JSONResponse(
129-
status_code=status.HTTP_200_OK, content=json.loads(cached_data, use_decimal=True, parse_nan=True)
132+
status_code=status.HTTP_200_OK,
133+
content=json.loads(cached_data, use_decimal=True, parse_nan=True),
130134
)
131135

132136
xquery = selectQuery(
@@ -168,7 +172,8 @@ async def selectRecordCheckpoints(
168172
if cached_data is not None:
169173
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
170174
return JSONResponse(
171-
status_code=status.HTTP_200_OK, content=json.loads(cached_data, use_decimal=True, parse_nan=True)
175+
status_code=status.HTTP_200_OK,
176+
content=json.loads(cached_data, use_decimal=True, parse_nan=True),
172177
)
173178

174179
xquery = selectQuery(
@@ -211,18 +216,19 @@ async def deleteCheckpoints(
211216
content_data = {"deleted": xquery, "xtime": time.perf_counter() - tic}
212217
if xquery < 1:
213218
# response.body = json.dumps(content_data).encode('utf-8')
214-
response.headers['content-type'] = 'application/json'
219+
response.headers["content-type"] = "application/json"
215220
response.status_code = status.HTTP_304_NOT_MODIFIED
216221
return response
217222

218223
toc = time.perf_counter()
219224
print(f"Execution time {toc - tic:0.4f}")
220225

221-
response.body = json.dumps(content_data).encode('utf-8')
222-
response.headers['content-type'] = 'application/json'
226+
response.body = json.dumps(content_data).encode("utf-8")
227+
response.headers["content-type"] = "application/json"
223228
response.status_code = status.HTTP_200_OK
224229
return response
225230

231+
226232
@router.get(
227233
"/surftimer/selectStageTimes",
228234
name="Get Stage Times",
@@ -240,7 +246,8 @@ async def selectStageTimes(
240246
if cached_data is not None:
241247
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
242248
return JSONResponse(
243-
status_code=status.HTTP_200_OK, content=json.loads(cached_data, use_decimal=True, parse_nan=True)
249+
status_code=status.HTTP_200_OK,
250+
content=json.loads(cached_data, use_decimal=True, parse_nan=True),
244251
)
245252

246253
xquery = selectQuery(
@@ -280,7 +287,8 @@ async def selectStageAttempts(
280287
if cached_data is not None:
281288
print(f"[Redis] Loaded '{cache_key}' ({time.perf_counter() - tic:0.4f}s)")
282289
return JSONResponse(
283-
status_code=status.HTTP_200_OK, content=json.loads(cached_data, use_decimal=True, parse_nan=True)
290+
status_code=status.HTTP_200_OK,
291+
content=json.loads(cached_data, use_decimal=True, parse_nan=True),
284292
)
285293

286294
xquery = selectQuery(

surftimer/ck_latestrecords.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,14 @@
1212

1313

1414
class LatestRec(BaseModel):
15+
"""Body for adding or updating **latest record** entries"""
16+
1517
steamid32: str
1618
name: str
1719
runtime: Decimal
1820
mapname: str
1921

22+
2023
# ck_latestrecords
2124
@router.get(
2225
"/surftimer/selectLatestRecords",
@@ -61,11 +64,7 @@ async def selectLatestRecord(request: Request, response: Response):
6164
name="Add Latest Record",
6265
tags=["ck_latestrecords"],
6366
)
64-
async def insertLatestRecord(
65-
request: Request,
66-
response: Response,
67-
data: LatestRec
68-
):
67+
async def insertLatestRecord(request: Request, response: Response, data: LatestRec):
6968
"""Inserts a new record to the table\n
7069
```char sql_insertLatestRecords[] = ....```"""
7170
tic = time.perf_counter()
@@ -76,18 +75,18 @@ async def insertLatestRecord(
7675
xquery = insertQuery(sql)
7776
# xquery = 0
7877
# time.sleep(3)
79-
78+
8079
content_data = {"inserted": xquery, "xtime": time.perf_counter() - tic}
8180
if xquery < 1:
8281
# response.body = json.dumps(content_data).encode('utf-8')
83-
response.headers['content-type'] = 'application/json'
82+
response.headers["content-type"] = "application/json"
8483
response.status_code = status.HTTP_304_NOT_MODIFIED
8584
return response
8685

8786
# Prepare the response
8887
toc = time.perf_counter()
8988
print(f"Execution time {toc - tic:0.4f}")
9089

91-
response.body = json.dumps(content_data).encode('utf-8')
90+
response.body = json.dumps(content_data).encode("utf-8")
9291
response.status_code = status.HTTP_201_CREATED
9392
return response

0 commit comments

Comments
 (0)