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() 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: try:
with open(filename, 'r') as f: with open(filename, "r") as f:
data = json.load(f) data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
data = [] data = []
data.append(last_request) data.append(last_request)
if len(data) > LIMIT: if len(data) > HISTORY_LIMIT:
data.pop(0) data.pop(0)
with open(filename, 'w') as f: with open(filename, "w") as f:
json.dump(data, f) json.dump(data, f)
@app.post("/", status_code=status.HTTP_200_OK) @app.post("/", status_code=status.HTTP_200_OK)
async def webhook_handler(request: Request, response: Response): 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) store_last_request(last_request)
response.status_code = status.HTTP_200_OK response.status_code = status.HTTP_200_OK
return {"status": "ok"} return {"status": "ok"}
@app.get("/__last_request__", status_code=status.HTTP_200_OK) @app.get("/__last_request__", status_code=status.HTTP_200_OK)
async def last_requests(): async def last_requests():
try: try:
with open('requests.json', 'r') as f: with open(HISTORY_FILE, "r") as f:
data = json.load(f) data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
data = [] data = []
return data[-1:] return data[-1:]
@app.get("/__history__", status_code=status.HTTP_200_OK) @app.get("/__history__", status_code=status.HTTP_200_OK)
async def history(): async def history():
try: try:
with open('requests.json', 'r') as f: with open(HISTORY_FILE, "r") as f:
data = json.load(f) data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
data = [] data = []

20
compose.yml Normal file
View File

@@ -0,0 +1,20 @@
networks:
apps-proxy:
external: true
name: apps-proxy
services:
catcher:
image: shadoll/scatcher
volumes:
- ./storage:/app/storage
networks:
- "apps-proxy"
labels:
traefik.enable: true
traefik.docker.network: apps-proxy
traefik.http.routers.catcher.entrypoints: websecure
traefik.http.routers.catcher.rule: Host(`catcher.rs.shadoll.dev`)
traefik.http.routers.catcher.tls: true
traefik.http.routers.catcher.tls.certresolver: letsencrypt
traefik.http.services.catcher.loadbalancer.server.port: 5000