Files
f1-circuits/cdn-api.py
T
jschoubben d514eb57a3 Name an unknown circuit, layout or year with a 404 instead of a 500
The circuit and track routes walked circuits.json with chained lookups, so an unknown country, locality, circuit
or layout, or a year no layout covers, raised and answered 500 (/circuits/photos.json among them). One lookup now
names the first unknown part and the API answers it 404. numpy loads only where a script uses it, so the models,
and this lookup's test, need the standard library alone.

Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh
2026-11-27 15:13:34 +01:00

312 lines
14 KiB
Python

from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from typing import Optional
import logging
# Import our CircuitService
from app_info import APP_VERSION
from circuits_service import CircuitService, Format, NotFound
from posters_service import PostersService, Rendered
import poster_options
import poster_sources
from access_log import log_request
from models.track_layout import TrackLayout
# The unofficial-use disclaimer for the Formula 1 marks, at the foot of / and /docs (and of the example site).
DISCLAIMER = ("This service is unofficial and is not associated in any way with the Formula 1 companies. F1, FORMULA "
"ONE, FORMULA 1, FIA FORMULA ONE WORLD CHAMPIONSHIP, GRAND PRIX, and related marks are trademarks of "
"Formula One Licensing B.V.")
# Initialize FastAPI app; /docs is served below, with the disclaimer at its foot
app = FastAPI(
title="F1 Track Layouts API",
description="API serving F1 track layout images, vectors and GeoJSON files",
version=APP_VERSION,
docs_url=None,
)
# Add CORS middleware. The example pages, opened from another origin, read a picture's credits and licence.
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["X-Credits", "X-License", "Link", "ETag"],
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# One line per request (uvicorn's own access log is off: --no-access-log)
app.middleware("http")(log_request)
# Initialize CircuitService
circuit_service = CircuitService()
# One Jolpica client for the whole service, so its schedules and its pacing are shared
ergast_service = circuit_service.ergast_service
posters_service = PostersService(circuit_service, ergast_service)
def get_content_disposition(format: Format) -> str:
if format == Format.PNG:
return "inline"
# SVG and GeoJSON files as attachments for security/convention
return "attachment"
def get_media_type(format: Format) -> str:
media_types = {
Format.PNG: "image/png",
Format.SVG: "image/svg+xml",
Format.GEOJSON: "application/geo+json"
}
return media_types.get(format, "application/octet-stream") # fallback for unknown formats
def get_relative_filepath(layout: TrackLayout, format: Format) -> Path:
# Each format serves its own file: the PNG, the SVG, or the GPS-traced GeoJSON
relative_filepaths = {
Format.PNG: layout.relative_png_filepath,
Format.SVG: layout.relative_svg_filepath,
Format.GEOJSON: layout.relative_geojson_filepath,
}
return relative_filepaths[format]
@app.get("/")
async def root():
"""Root endpoint returning API information"""
return {
"name": "F1 Track Layouts API",
"version": "1.0.0",
"endpoints": [
"/circuits",
"/circuits/{country_slug}",
"/circuits/{country_slug}/{city_slug}",
"/circuits/{country_slug}/{city_slug}/{circuit_slug}",
"/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}",
"/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{format}",
"/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{format}",
"/grand-prix/{grand_prix_name}/{season}/{format}",
"/posters/race/{grand_prix_name}/{season}.png",
"/posters/season/{season}.png",
"/posters/session/{grand_prix_name}/{season}/{session_slug}.png",
"/kometa/formula-1-metadata.yml",
"/licences",
],
"examples": "/examples/",
"disclaimer": DISCLAIMER,
}
@app.get("/docs", include_in_schema=False)
async def docs() -> HTMLResponse:
"""The OpenAPI docs, with the disclaimer at their foot."""
page = get_swagger_ui_html(openapi_url=app.openapi_url, title=f"{app.title} - docs").body.decode()
footer = (f'<footer style="font-family: sans-serif; font-size: 12px; color: #666; margin: 2em; '
f'text-align: center">{DISCLAIMER}</footer>')
return HTMLResponse(page.replace("</body>", f"{footer}</body>"))
@app.get("/licences")
async def get_licences():
"""Every source a picture may be made from: its licence, its credit and its terms' address, and how a picture's
licence follows from them."""
return poster_sources.licences()
# The example site: one page per area of the API, each calling the routes above (examples/index.html).
app.mount(
"/examples",
StaticFiles(directory=Path(__file__).resolve().parent / "examples", html=True),
name="examples",
)
# The poster routes are plain defs, not async: a render fetches map tiles and a schedule and draws for
# seconds, so it runs in the threadpool instead of holding up every other request on the event loop.
POSTER_OPTIONS_DOC = """Options are query parameters, the same on every poster route (docs/posters.md); an unknown option
or value is answered 422, naming it: `style` (classic, minimal), `bg` (satellite, its alias aerial, osm, dark,
light, none), `photo` (natural, bw), `show` (a comma list of wordmark, round, name, subtitle, date, circuit,
locality, session), `locator` and `checker` (on, off), `track` (off, or #rrggbb with an optional width:
#ffffff,6), `dim` (0 to 1), `accent` (#rrggbb), `width` (200 up to the frame's), `format` (png, jpg, webp), and
`v`, the render version, which the Kometa file adds so clients keep the picture for good."""
def render_poster(request: Request, kind: str, grand_prix_name: Optional[str] = None, season: Optional[int] = None,
session_slug: Optional[str] = None) -> Response:
"""A picture with its credits, its licence and what clients may keep of it.
An address with the current render version (?v=) is kept for good; any other a day, then asked again with its
ETag (a 304 while it is unchanged); a picture served without its map or photo five minutes, with no ETag."""
try:
options = poster_options.parse_options(request.query_params.multi_items(), kind)
except poster_options.OptionError as e:
return JSONResponse(status_code=422, content={"detail": str(e)})
try:
rendered: Optional[Rendered] = posters_service.render(kind, options, grand_prix_name, season, session_slug)
except poster_sources.LicenceClash as e:
logger.error(f"Picture refused, {kind} {grand_prix_name} {season} {session_slug}: {e}")
raise HTTPException(status_code=500, detail=f"Picture refused: {e}")
if rendered is None:
what = " ".join(str(part) for part in (grand_prix_name, season, session_slug) if part is not None)
raise HTTPException(status_code=404, detail=f"No {kind} picture available for {what}")
etag = '"' + rendered.name.split(".")[0][:32] + '"'
headers = poster_options.cache_headers(rendered.kept, options.versioned, etag)
headers.update({"X-Credits": poster_sources.ascii_header(rendered.credit), "X-License": rendered.licence,
"Link": '</licences>; rel="license"'})
if rendered.kept and poster_options.etag_matches(request.headers.get("if-none-match", ""), etag):
return Response(status_code=304, headers=headers)
return Response(content=rendered.data, media_type=rendered.media_type, headers=headers)
@app.get("/posters/race/{grand_prix_name}/{season}.png", description=POSTER_OPTIONS_DOC)
def get_race_poster(request: Request, grand_prix_name: str, season: int):
"""Plex-ready 1000x1500 race poster: the round, the race's name and date and its track over a map or photo of
its circuit."""
return render_poster(request, "race", grand_prix_name, season)
@app.get("/posters/season/{season}.png", description=POSTER_OPTIONS_DOC)
def get_season_poster(request: Request, season: int):
"""Plex-ready 1000x1500 season poster: the year over a picked photo of that season's cars, or over black."""
return render_poster(request, "season", season=season)
@app.get("/posters/session/{grand_prix_name}/{season}/{session_slug}.png", description=POSTER_OPTIONS_DOC)
def get_session_thumb(request: Request, grand_prix_name: str, season: int, session_slug: str):
"""Plex episode-thumb (1920x1080) for one session of a race weekend.
`session_slug` is one of: fp1, fp2, fp3, pre-qualifying, qualifying,
post-qualifying, pre-race, race, post-race, highlights, pre-sprint,
sprint, post-sprint, pre-sprint-qualifying, sprint-qualifying,
post-sprint-qualifying, bonus.
"""
return render_poster(request, "session", grand_prix_name, season, session_slug)
@app.get("/kometa/formula-1-metadata.yml")
def get_kometa_metadata():
"""Generate a Kometa-compatible metadata YAML for the Formula 1 library.
Its first lines say where its data comes from (Jolpica, CC BY-NC-SA 4.0). One entry per F1 season from
1950..current+1. Each entry:
- uses Kometa's f1_season builder for round/episode names
- sets url_poster on the show (the season poster)
- sets url_poster on each Plex 'season' (== each F1 round) from the race poster route, and on each episode
from the session thumbnail route; every address carries ?v=<render version>
Kometa harmlessly skips shows / seasons that don't exist in the Plex
library, so we can emit the full schedule and let Kometa do the matching.
A plain def, not async: the first call asks Jolpica for every season, paced under its rate
limit (about 25 s), and runs in the threadpool instead of holding up every other request.
"""
yaml = posters_service.render_kometa_metadata()
return PlainTextResponse(
content=yaml,
media_type="text/yaml; charset=utf-8",
# YAML changes only when the Jolpica schedule changes — cache 1h.
headers={"Cache-Control": "public, max-age=3600"},
)
@app.get("/circuits")
async def get_countries():
"""Get list of all available countries with their slugs"""
return {
"countries": [c.to_dict() for c in circuit_service.get_countries_list()]
}
@app.exception_handler(NotFound)
async def not_found(request: Request, error: NotFound) -> JSONResponse:
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: named."""
return JSONResponse(status_code=404, content={"detail": str(error)})
@app.get("/circuits/{country_slug}")
async def get_cities(country_slug: str):
"""Get list of cities for a specific country"""
return {"cities": [c.to_dict() for c in circuit_service.get_localities_list(country_slug)]}
@app.get("/circuits/{country_slug}/{city_slug}")
async def get_circuits(country_slug: str, city_slug: str):
"""Get list of circuits for a specific city"""
return {"circuits": [c.to_dict() for c in circuit_service.get_circuits_list(country_slug, city_slug)]}
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}")
async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str):
"""Get circuit details and available formats"""
return circuit_service.resolve(country_slug, city_slug, circuit_slug).to_dict()
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}")
async def get_layout_details(country_slug: str, city_slug: str, circuit_slug: str, layout_slug: str):
"""Get details for a specific layout"""
return circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug).to_dict()
@app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}")
async def get_track_by_year(
country_slug: str,
city_slug: str,
circuit_slug: str,
year: int,
image_format: Format,
response: Response
):
"""Get track layout for a specific year"""
return get_file_response(circuit_service.layout_for_year(country_slug, city_slug, circuit_slug, year),
image_format, response)
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}")
async def get_track_by_layout(
country_slug: str,
city_slug: str,
circuit_slug: str,
layout_slug: str,
image_format: Format,
response: Response
):
"""Get specific track layout"""
return get_file_response(circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug),
image_format, response)
@app.get("/grand-prix/{grand_prix_name}/{season}/{image_format}")
def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
layout = circuit_service.get_circuit_layout_by_ergast_data(grand_prix_name, season)
if not layout:
raise HTTPException(status_code=404, detail="Circuit not found")
try:
return get_file_response(layout, image_format, response)
except KeyError as e:
logger.error(f"KeyError in get_track_by_year: {str(e)}")
raise HTTPException(status_code=404, detail="Circuit or layout not found")
def get_file_response(layout: TrackLayout, image_format: Format, response: Response) -> FileResponse:
# layout = circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug)
file_path = Path(f"./circuits").joinpath(get_relative_filepath(layout, image_format))
if not file_path or not file_path.exists():
logger.error(f"File not found: {file_path}")
logger.info(f"Looking for {layout.slug} in format {image_format}")
raise HTTPException(status_code=404, detail=f"File not found in {image_format} format")
# Get actual filename from the path for the Content-Disposition header
filename = file_path.name
logger.info(f"Serving file: {file_path}")
return FileResponse(
file_path,
media_type=get_media_type(image_format),
content_disposition_type=get_content_disposition(image_format),
filename=filename,
headers={
"Cache-Control": "public, max-age=31536000",
"ETag": f"{layout.circuit.locality.country.slug}/{layout.circuit.locality.slug}/{layout.circuit.slug}-{layout.slug}-{image_format}"
}
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)