Skip to content

Commit

Permalink
Add builds for all heroes
Browse files Browse the repository at this point in the history
  • Loading branch information
raimannma committed Sep 20, 2024
1 parent 1441081 commit ba06810
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 14 deletions.
17 changes: 10 additions & 7 deletions deadlock_api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@

from discord_webhook import DiscordWebhook
from fastapi import FastAPI
from pydantic import TypeAdapter
from starlette.responses import RedirectResponse, Response

from deadlock_api.models.active_match import ActiveMatch, APIActiveMatch
from deadlock_api.models.build import APIBuild, Build
from deadlock_api.models.build import Build

WEBHOOK_URL = "https://discord.com/api/webhooks/1286415194427363380/Bb5mGAqn1yicXzRigxOkyYxZiGsL1AXI-PqxMf7Z7oxqTh4wBsN1oGHThbDGhKNZ9NAC"
WEBHOOK = DiscordWebhook(url=WEBHOOK_URL)
Expand All @@ -21,7 +22,8 @@ class State:

logging.basicConfig(level=logging.INFO)

CACHE_AGE = 30
CACHE_AGE_ACTIVE_MATCHES = 30
CACHE_AGE_BUILDS = CACHE_AGE_ACTIVE_MATCHES * 12

app = FastAPI()

Expand All @@ -32,13 +34,14 @@ def redirect_to_docs():


@app.get("/builds")
def get_builds(response: Response) -> list[Build]:
def get_builds(response: Response) -> dict[str, list[Build]]:
last_modified = os.path.getmtime("builds.json")
cache_time = dynamic_cache_time(last_modified)
response.headers["Cache-Control"] = f"public, max-age={cache_time}"
response.headers["Last-Updated"] = str(int(last_modified))
ta = TypeAdapter(dict[str, list[Build]])
with open("builds.json") as f:
return APIBuild.model_validate_json(f.read()).results
return ta.validate_json(f.read())


@app.get("/active-matches")
Expand All @@ -54,14 +57,14 @@ def get_active_matches(response: Response) -> list[ActiveMatch]:
def dynamic_cache_time(last_modified: float) -> int:
age = time.time() - last_modified

if age < CACHE_AGE:
if age < CACHE_AGE_ACTIVE_MATCHES:
if APP_STATE.is_up is False:
WEBHOOK.content = f"Data is now up to date"
WEBHOOK.execute()
APP_STATE.is_up = True
return int(CACHE_AGE - age)
return int(CACHE_AGE_ACTIVE_MATCHES - age)

if age > 2 * CACHE_AGE:
if age > 2 * CACHE_AGE_ACTIVE_MATCHES:
print("Data is stale")
if APP_STATE.is_up:
WEBHOOK.content = f"Data last updated {int(age)} seconds ago"
Expand Down
7 changes: 0 additions & 7 deletions deadlock_api/models/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,3 @@ class Build(BaseModel):
num_favorites: int
num_ignores: int
num_reports: int


class APIBuild(BaseModel):
model_config = ConfigDict(populate_by_name=True)

response: int
results: list[Build]

0 comments on commit ba06810

Please sign in to comment.