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
This commit is contained in:
@@ -41,6 +41,8 @@ else EOxCloudless; [circuits/photos.json](circuits/photos.json) holds the picks,
|
|||||||
layout draw the dark map instead of EOxCloudless. Every picture carries the credit line of its sources at its
|
layout draw the dark map instead of EOxCloudless. Every picture carries the credit line of its sources at its
|
||||||
bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: </licences>; rel="license"`.
|
bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: </licences>; rel="license"`.
|
||||||
|
|
||||||
|
An unknown country, locality, circuit or layout, or a year no layout of the circuit covers, is answered 404, naming it.
|
||||||
|
|
||||||
A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in
|
A race is named as [Jolpica](https://github.com/jolpica/jolpica-f1) (the Ergast API's successor) names it in
|
||||||
its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the
|
its schedule, and its circuit is found by Jolpica's circuit id (`ergastId` in `circuits.json`), never by the
|
||||||
circuit's name: Jolpica renames circuits (Losail became Lusail), the id stays.
|
circuit's name: Jolpica renames circuits (Losail became Lusail), the id stays.
|
||||||
@@ -163,7 +165,7 @@ are fetched only when a picture asks for them, at most two at once; Wikimedia Co
|
|||||||
|
|
||||||
`merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in
|
`merge-check.sh` runs before a change merges: every Python file the service ships must parse, and the tests in
|
||||||
`tests/` must pass (every circuit has one unique `ergastId`, a race resolves by it, a failed Jolpica fetch is never
|
`tests/` must pass (every circuit has one unique `ergastId`, a race resolves by it, a failed Jolpica fetch is never
|
||||||
kept, every link in this README leads to a file; a poster's satellite source,
|
kept, every link in this README leads to a file, an unknown circuit or layout is named; a poster's satellite source,
|
||||||
credits and licence, its options, keys and cache headers, and the picture store's cap).
|
credits and licence, its options, keys and cache headers, and the picture store's cap).
|
||||||
|
|
||||||
## Acknowledgment
|
## Acknowledgment
|
||||||
|
|||||||
+15
-28
@@ -9,7 +9,7 @@ import logging
|
|||||||
|
|
||||||
# Import our CircuitService
|
# Import our CircuitService
|
||||||
from app_info import APP_VERSION
|
from app_info import APP_VERSION
|
||||||
from circuits_service import CircuitService, Format
|
from circuits_service import CircuitService, Format, NotFound
|
||||||
from posters_service import PostersService, Rendered
|
from posters_service import PostersService, Rendered
|
||||||
import poster_options
|
import poster_options
|
||||||
import poster_sources
|
import poster_sources
|
||||||
@@ -220,37 +220,31 @@ async def get_countries():
|
|||||||
"countries": [c.to_dict() for c in circuit_service.get_countries_list()]
|
"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}")
|
@app.get("/circuits/{country_slug}")
|
||||||
async def get_cities(country_slug: str):
|
async def get_cities(country_slug: str):
|
||||||
"""Get list of cities for a specific country"""
|
"""Get list of cities for a specific country"""
|
||||||
cities = circuit_service.get_localities_list(country_slug)
|
return {"cities": [c.to_dict() for c in circuit_service.get_localities_list(country_slug)]}
|
||||||
if not cities:
|
|
||||||
raise HTTPException(status_code=404, detail="Country not found")
|
|
||||||
return {"cities": [c.to_dict() for c in cities]}
|
|
||||||
|
|
||||||
@app.get("/circuits/{country_slug}/{city_slug}")
|
@app.get("/circuits/{country_slug}/{city_slug}")
|
||||||
async def get_circuits(country_slug: str, city_slug: str):
|
async def get_circuits(country_slug: str, city_slug: str):
|
||||||
"""Get list of circuits for a specific city"""
|
"""Get list of circuits for a specific city"""
|
||||||
circuits = circuit_service.get_circuits_list(country_slug, city_slug)
|
return {"circuits": [c.to_dict() for c in circuit_service.get_circuits_list(country_slug, city_slug)]}
|
||||||
if not circuits:
|
|
||||||
raise HTTPException(status_code=404, detail="City not found")
|
|
||||||
return {"circuits": [c.to_dict() for c in circuits]}
|
|
||||||
|
|
||||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}")
|
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}")
|
||||||
async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str):
|
async def get_circuit_details(country_slug: str, city_slug: str, circuit_slug: str):
|
||||||
"""Get circuit details and available formats"""
|
"""Get circuit details and available formats"""
|
||||||
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug)
|
return circuit_service.resolve(country_slug, city_slug, circuit_slug).to_dict()
|
||||||
if not circuit_details:
|
|
||||||
raise HTTPException(status_code=404, detail="Circuit not found")
|
|
||||||
return circuit_details.to_dict()
|
|
||||||
|
|
||||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}")
|
@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):
|
async def get_layout_details(country_slug: str, city_slug: str, circuit_slug: str, layout_slug: str):
|
||||||
"""Get details for a specific layout"""
|
"""Get details for a specific layout"""
|
||||||
layout_details = circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug)
|
return circuit_service.resolve(country_slug, city_slug, circuit_slug, layout_slug).to_dict()
|
||||||
if not layout_details:
|
|
||||||
raise HTTPException(status_code=404, detail="Layout not found")
|
|
||||||
return layout_details.to_dict()
|
|
||||||
|
|
||||||
@app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}")
|
@app.get("/tracks/{country_slug}/{city_slug}/{circuit_slug}/year/{year}/{image_format}")
|
||||||
async def get_track_by_year(
|
async def get_track_by_year(
|
||||||
@@ -262,16 +256,8 @@ async def get_track_by_year(
|
|||||||
response: Response
|
response: Response
|
||||||
):
|
):
|
||||||
"""Get track layout for a specific year"""
|
"""Get track layout for a specific year"""
|
||||||
circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug)
|
return get_file_response(circuit_service.layout_for_year(country_slug, city_slug, circuit_slug, year),
|
||||||
if not circuit_details:
|
image_format, response)
|
||||||
raise HTTPException(status_code=404, detail="Circuit not found")
|
|
||||||
|
|
||||||
try:
|
|
||||||
layout_slug = circuit_service.find_layout_slug_for_year(circuit_details, year)
|
|
||||||
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), 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")
|
|
||||||
|
|
||||||
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}")
|
@app.get("/circuits/{country_slug}/{city_slug}/{circuit_slug}/layout/{layout_slug}/{image_format}")
|
||||||
async def get_track_by_layout(
|
async def get_track_by_layout(
|
||||||
@@ -283,7 +269,8 @@ async def get_track_by_layout(
|
|||||||
response: Response
|
response: Response
|
||||||
):
|
):
|
||||||
"""Get specific track layout"""
|
"""Get specific track layout"""
|
||||||
return get_file_response(circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug), image_format, response)
|
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}")
|
@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):
|
def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response):
|
||||||
|
|||||||
+51
-13
@@ -12,6 +12,11 @@ from models.model_builder import parse_circuits_json
|
|||||||
from models.track_layout import TrackLayout
|
from models.track_layout import TrackLayout
|
||||||
|
|
||||||
|
|
||||||
|
class NotFound(LookupError):
|
||||||
|
"""A country, locality, circuit or layout circuits.json does not hold, or a year no layout covers: answered 404,
|
||||||
|
naming it."""
|
||||||
|
|
||||||
|
|
||||||
# Define supported formats
|
# Define supported formats
|
||||||
class Format(str, Enum):
|
class Format(str, Enum):
|
||||||
PNG = "png"
|
PNG = "png"
|
||||||
@@ -69,6 +74,31 @@ class CircuitService:
|
|||||||
return layout_slug
|
return layout_slug
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
def resolve(self, country_slug: str, locality_slug: Optional[str] = None, circuit_slug: Optional[str] = None,
|
||||||
|
layout_slug: Optional[str] = None):
|
||||||
|
"""The country, locality, circuit or layout the given slugs lead to (the deepest one given); NotFound names
|
||||||
|
the first that circuits.json does not hold."""
|
||||||
|
found = self.circuit_data.get(country_slug)
|
||||||
|
if found is None:
|
||||||
|
raise NotFound(f"No country {country_slug!r}")
|
||||||
|
for kind, slug, children in (("locality", locality_slug, "localities"), ("circuit", circuit_slug, "circuits"),
|
||||||
|
("layout", layout_slug, "layouts")):
|
||||||
|
if slug is None:
|
||||||
|
return found
|
||||||
|
parent = found
|
||||||
|
found = getattr(parent, children).get(slug)
|
||||||
|
if found is None:
|
||||||
|
raise NotFound(f"No {kind} {slug!r} in {getattr(parent, 'name', None) or getattr(parent, 'slug', '')}")
|
||||||
|
return found
|
||||||
|
|
||||||
|
def layout_for_year(self, country_slug: str, locality_slug: str, circuit_slug: str, year: int) -> TrackLayout:
|
||||||
|
"""The layout a circuit used in a year; NotFound when the circuit is unknown or no layout covers the year."""
|
||||||
|
circuit = self.resolve(country_slug, locality_slug, circuit_slug)
|
||||||
|
layout_slug = self.find_layout_slug_for_year(circuit, year)
|
||||||
|
if layout_slug is None:
|
||||||
|
raise NotFound(f"No layout of {circuit.name} covers {year}")
|
||||||
|
return circuit.layouts[layout_slug]
|
||||||
|
|
||||||
def get_countries_list(self) -> Optional[list[Country]]:
|
def get_countries_list(self) -> Optional[list[Country]]:
|
||||||
"""Get list of all available countries with their slugs"""
|
"""Get list of all available countries with their slugs"""
|
||||||
return [country for _, country in self.circuit_data.items()]
|
return [country for _, country in self.circuit_data.items()]
|
||||||
@@ -77,26 +107,34 @@ class CircuitService:
|
|||||||
"""Get details for a specific country"""
|
"""Get details for a specific country"""
|
||||||
return self.circuit_data.get(country_slug)
|
return self.circuit_data.get(country_slug)
|
||||||
|
|
||||||
def get_localities_list(self, country_slug: str) -> Optional[list[Locality]]:
|
def get_localities_list(self, country_slug: str) -> list[Locality]:
|
||||||
"""Get list of cities for a specific country"""
|
"""The localities of a country; NotFound when it is unknown"""
|
||||||
return [locality for _, locality in self.circuit_data[country_slug].localities.items()]
|
return list(self.resolve(country_slug).localities.values())
|
||||||
|
|
||||||
def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]:
|
def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]:
|
||||||
"""Get details for a specific city"""
|
"""Get details for a specific city; None when it is unknown"""
|
||||||
return self.circuit_data[country_slug].localities.get(locality_slug)
|
try:
|
||||||
|
return self.resolve(country_slug, locality_slug)
|
||||||
|
except NotFound:
|
||||||
|
return None
|
||||||
|
|
||||||
def get_circuits_list(self, country_slug: str, locality_slug: str) -> Optional[list[Circuit]]:
|
def get_circuits_list(self, country_slug: str, locality_slug: str) -> list[Circuit]:
|
||||||
"""Get list of circuits for a specific city"""
|
"""The circuits of a locality; NotFound when it is unknown"""
|
||||||
return [circuit_data for _, circuit_data in self.circuit_data[country_slug].localities.get(locality_slug).circuits.items()]
|
return list(self.resolve(country_slug, locality_slug).circuits.values())
|
||||||
|
|
||||||
def get_circuit_details(self, country_slug: str, locality_slug: str, circuit_slug: str) -> Optional[Circuit]:
|
def get_circuit_details(self, country_slug: str, locality_slug: str, circuit_slug: str) -> Optional[Circuit]:
|
||||||
"""Get circuit details and available formats"""
|
"""Get circuit details and available formats; None when it is unknown"""
|
||||||
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug)
|
try:
|
||||||
|
return self.resolve(country_slug, locality_slug, circuit_slug)
|
||||||
|
except NotFound:
|
||||||
|
return None
|
||||||
|
|
||||||
def get_layout_details(self, country_slug: str, locality_slug: str, circuit_slug: str, layout_slug: str) -> Optional[TrackLayout]:
|
def get_layout_details(self, country_slug: str, locality_slug: str, circuit_slug: str, layout_slug: str) -> Optional[TrackLayout]:
|
||||||
"""Get details for a specific layout"""
|
"""Get details for a specific layout; None when it is unknown"""
|
||||||
return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug).layouts.get(
|
try:
|
||||||
layout_slug)
|
return self.resolve(country_slug, locality_slug, circuit_slug, layout_slug)
|
||||||
|
except NotFound:
|
||||||
|
return None
|
||||||
|
|
||||||
def get_circuit_layout_by_ergast_data(self, grand_prix_name: str, season: int) -> Optional[TrackLayout]:
|
def get_circuit_layout_by_ergast_data(self, grand_prix_name: str, season: int) -> Optional[TrackLayout]:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import List, Dict, Any
|
from typing import List, Dict, Any
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class GeoJSONGeometry:
|
class GeoJSONGeometry:
|
||||||
@@ -18,6 +16,8 @@ class GeoJSONGeometry:
|
|||||||
|
|
||||||
def find_longest_straight(self, window_size=5) -> (List[float], List[float]):
|
def find_longest_straight(self, window_size=5) -> (List[float], List[float]):
|
||||||
"""Find the longest approximately straight section of the track, including wrap-around."""
|
"""Find the longest approximately straight section of the track, including wrap-around."""
|
||||||
|
import numpy as np # only here: the models themselves load with the standard library (the service's tests)
|
||||||
|
|
||||||
max_distance = 0
|
max_distance = 0
|
||||||
best_start_idx = 0
|
best_start_idx = 0
|
||||||
n = len(self.coordinates)
|
n = len(self.coordinates)
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
"""An unknown country, locality, circuit or layout, or a year no layout covers, is named (the API answers it 404).
|
||||||
|
|
||||||
|
Standard library only: the models load numpy only where a script uses it.
|
||||||
|
"""
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from circuits_service import CircuitService, NotFound
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
class LookupTest(unittest.TestCase):
|
||||||
|
def test_the_first_unknown_part_is_named(self):
|
||||||
|
service = CircuitService(str(ROOT / "circuits" / "circuits.json"))
|
||||||
|
spa = ("belgium", "spa", "circuit-de-spa-francorchamps")
|
||||||
|
self.assertEqual(service.resolve(*spa, "1983-").slug, "1983-")
|
||||||
|
self.assertEqual(service.layout_for_year(*spa, 1960).slug, "1950-1970")
|
||||||
|
cases = {
|
||||||
|
("photos.json",): "No country 'photos.json'",
|
||||||
|
("belgium", "nowhere"): "No locality 'nowhere' in Belgium",
|
||||||
|
("belgium", "spa", "nothing"): "No circuit 'nothing' in Spa",
|
||||||
|
(*spa, "1999"): "No layout '1999' in Circuit de Spa-Francorchamps",
|
||||||
|
}
|
||||||
|
for slugs, named in cases.items():
|
||||||
|
with self.assertRaises(NotFound, msg=slugs) as caught:
|
||||||
|
service.resolve(*slugs)
|
||||||
|
self.assertEqual(str(caught.exception), named)
|
||||||
|
with self.assertRaises(NotFound) as caught:
|
||||||
|
service.layout_for_year(*spa, 1975) # Spa was not raced from 1971 to 1982
|
||||||
|
self.assertEqual(str(caught.exception), "No layout of Circuit de Spa-Francorchamps covers 1975")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user