diff --git a/README.md b/README.md index 2e9e7b0..6261e73 100644 --- a/README.md +++ b/README.md @@ -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 bottom and in `X-Credits`, its licence in `X-License` (it follows its sources), and `Link: ; 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 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. @@ -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 `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). ## Acknowledgment diff --git a/cdn-api.py b/cdn-api.py index 201e0e1..e1026e3 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -9,7 +9,7 @@ import logging # Import our CircuitService 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 import poster_options import poster_sources @@ -220,37 +220,31 @@ async def get_countries(): "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""" - cities = 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]} + 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""" - circuits = 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]} + 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""" - circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug) - if not circuit_details: - raise HTTPException(status_code=404, detail="Circuit not found") - return circuit_details.to_dict() + 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""" - layout_details = circuit_service.get_layout_details(country_slug, city_slug, circuit_slug, layout_slug) - if not layout_details: - raise HTTPException(status_code=404, detail="Layout not found") - return layout_details.to_dict() + 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( @@ -262,16 +256,8 @@ async def get_track_by_year( response: Response ): """Get track layout for a specific year""" - circuit_details = circuit_service.get_circuit_details(country_slug, city_slug, circuit_slug) - if not circuit_details: - 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") + 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( @@ -283,7 +269,8 @@ async def get_track_by_layout( response: Response ): """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}") def get_grand_prix_circuit(grand_prix_name: str, season: int, image_format: Format, response: Response): diff --git a/circuits_service.py b/circuits_service.py index 2f3cb05..34eebfb 100644 --- a/circuits_service.py +++ b/circuits_service.py @@ -12,6 +12,11 @@ from models.model_builder import parse_circuits_json 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 class Format(str, Enum): PNG = "png" @@ -69,6 +74,31 @@ class CircuitService: return layout_slug 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]]: """Get list of all available countries with their slugs""" return [country for _, country in self.circuit_data.items()] @@ -77,26 +107,34 @@ class CircuitService: """Get details for a specific country""" return self.circuit_data.get(country_slug) - def get_localities_list(self, country_slug: str) -> Optional[list[Locality]]: - """Get list of cities for a specific country""" - return [locality for _, locality in self.circuit_data[country_slug].localities.items()] + def get_localities_list(self, country_slug: str) -> list[Locality]: + """The localities of a country; NotFound when it is unknown""" + return list(self.resolve(country_slug).localities.values()) def get_locality_details(self, country_slug: str, locality_slug: str) -> Optional[Locality]: - """Get details for a specific city""" - return self.circuit_data[country_slug].localities.get(locality_slug) + """Get details for a specific city; None when it is unknown""" + 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]]: - """Get list of circuits for a specific city""" - return [circuit_data for _, circuit_data in self.circuit_data[country_slug].localities.get(locality_slug).circuits.items()] + def get_circuits_list(self, country_slug: str, locality_slug: str) -> list[Circuit]: + """The circuits of a locality; NotFound when it is unknown""" + 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]: - """Get circuit details and available formats""" - return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug) + """Get circuit details and available formats; None when it is unknown""" + 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]: - """Get details for a specific layout""" - return self.circuit_data[country_slug].localities.get(locality_slug).circuits.get(circuit_slug).layouts.get( - layout_slug) + """Get details for a specific layout; None when it is unknown""" + try: + 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]: """ diff --git a/models/geo_json/geometry.py b/models/geo_json/geometry.py index c6f967b..002dbec 100644 --- a/models/geo_json/geometry.py +++ b/models/geo_json/geometry.py @@ -1,8 +1,6 @@ from dataclasses import dataclass from typing import List, Dict, Any -import numpy as np - @dataclass class GeoJSONGeometry: @@ -18,6 +16,8 @@ class GeoJSONGeometry: def find_longest_straight(self, window_size=5) -> (List[float], List[float]): """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 best_start_idx = 0 n = len(self.coordinates) diff --git a/tests/test_lookups.py b/tests/test_lookups.py new file mode 100644 index 0000000..a1f4a05 --- /dev/null +++ b/tests/test_lookups.py @@ -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()