api/endpoints/counters.py

69 lines
1.6 KiB
Python
Raw Normal View History

2024-08-13 19:21:48 -04:00
#!/usr/bin/env python3.12
from fastapi import FastAPI
from pydantic import BaseModel
class ValidCounterIncrementRequest(BaseModel):
"""
- **counter**: counter to update
"""
counter: str
2024-08-13 19:39:54 -04:00
key: str
2024-08-13 19:21:48 -04:00
class ValidCounterRetrievalRequest(BaseModel):
"""
- **counter**: counter to retrieve (if none is provided, all counters are returned)
"""
counter: str = "all"
class Counters(FastAPI):
"""Counter Endpoints"""
def __init__(self, app: FastAPI, util, constants, glob_state): # pylint: disable=super-init-not-called
self.app = app
self.util = util
self.constants = constants
self.glob_state = glob_state
self.endpoints = {
"counters/get": self.get_counter_handler,
"counters/increment": self.increment_counter_handler
#tbd
}
for endpoint, handler in self.endpoints.items():
app.add_api_route(f"/{endpoint}/", handler, methods=["POST"])
async def get_counter_handler(self, data: ValidCounterRetrievalRequest):
"""
2024-08-13 19:39:54 -04:00
/counters/get/
2024-08-13 19:21:48 -04:00
Get current counter value
"""
counter = data.counter
if not counter == 'all':
count = await self.glob_state.get_counter(counter)
else:
count = await self.glob_state.get_all_counters()
return {
'counter': counter,
'count': count
}
async def increment_counter_handler(self, data: ValidCounterIncrementRequest):
"""
2024-08-13 19:39:54 -04:00
/counters/increment/
2024-08-13 19:21:48 -04:00
Increment counter value (requires PUT KEY)
"""
return {
}