Refactor request history storage and add Docker Compose file

This commit is contained in:
sHa
2024-03-12 16:38:32 +02:00
parent e9ad2f7c64
commit f37b33be9a
2 changed files with 32 additions and 8 deletions

20
app.py
View File

@@ -4,23 +4,26 @@ import json
app = FastAPI()
LIMIT = 10
HISTORY_LIMIT = 10
HISTORY_FILE = "storage/requests.json"
def store_last_request(last_request, filename='requests.json'):
def store_last_request(last_request, filename=HISTORY_FILE):
try:
with open(filename, 'r') as f:
with open(filename, "r") as f:
data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
data = []
data.append(last_request)
if len(data) > LIMIT:
if len(data) > HISTORY_LIMIT:
data.pop(0)
with open(filename, 'w') as f:
with open(filename, "w") as f:
json.dump(data, f)
@app.post("/", status_code=status.HTTP_200_OK)
async def webhook_handler(request: Request, response: Response):
@@ -35,25 +38,26 @@ async def webhook_handler(request: Request, response: Response):
}
store_last_request(last_request)
response.status_code = status.HTTP_200_OK
return {"status": "ok"}
@app.get("/__last_request__", status_code=status.HTTP_200_OK)
async def last_requests():
try:
with open('requests.json', 'r') as f:
with open(HISTORY_FILE, "r") as f:
data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
data = []
return data[-1:]
@app.get("/__history__", status_code=status.HTTP_200_OK)
async def history():
try:
with open('requests.json', 'r') as f:
with open(HISTORY_FILE, "r") as f:
data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
data = []