Coverage for src/anpr2mqtt/api_client.py: 95%
72 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-23 13:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-23 13:55 +0000
1import datetime as dt
2import re
3from email.utils import parsedate_to_datetime
4from pathlib import Path
5from typing import Any, Literal, cast
7import niquests
8import structlog
9from niquests_cache import CachedSession as _CachedSession
10from niquests_cache.backends import FileCache
12from anpr2mqtt.settings import CacheType
14log = structlog.get_logger()
17class APIClient:
18 def lookup(self, reg: str) -> dict[str, Any]:
19 raise NotImplementedError()
22class DVLAClient(APIClient):
23 ID = "GB"
24 REG_RE = r"(^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$)|(^[A-Z][0-9]{1,3}[A-Z]{3}$)|(^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(^[0-9]{1,4}[A-Z]{1,2}$)|(^[0-9]{1,3}[A-Z]{1,3}$)|(^[A-Z]{1,2}[0-9]{1,4}$)|(^[A-Z]{1,3}[0-9]{1,3}$)|(^[A-Z]{1,3}[0-9]{1,4}$)|(^[0-9]{3}[DX]{1}[0-9]{3}$)" # ruff: ignore[line-too-long]
25 """https://developer-portal.driver-vehicle-licensing.api.gov.uk"""
27 def __init__(
28 self,
29 api_key: str,
30 cache_ttl: int = 60 * 60 * 6,
31 cache_type: CacheType = CacheType.MEMORY,
32 cache_dir: Path | None = None,
33 verify_plate: str | None = None,
34 test: bool = False,
35 ) -> None:
36 self.cache_session: _CachedSession | None = None
37 if cache_type == CacheType.FILE and cache_dir:
38 try:
39 file_cache: FileCache = FileCache(cache_name=str(cache_dir), use_cache_dir=True)
40 log.debug("Caching DVLA at %s for %s", file_cache.cache_dir, cache_ttl)
41 self.cache_session = _CachedSession(
42 cache_name="dvla_cache", allowable_methods=["GET", "POST"], expire_after=cache_ttl, backend=file_cache
43 )
44 except Exception as e:
45 log.error("Unable to configure file system caching, reverting to in memory: %s", e)
46 cache_type = CacheType.MEMORY
48 if self.cache_session is None:
49 if cache_type != CacheType.MEMORY:
50 log.warn("Unable to cache DVLA as %s, falling back to in memory for %s", cache_type, cache_ttl)
51 else:
52 log.debug("Caching DVLA in memory for %s", cache_ttl)
53 self.cache_session = _CachedSession(
54 cache_name="dvla_cache", allowable_methods=["GET", "POST"], backend="memory", expire_after=cache_ttl
55 )
57 self.api_key: str = api_key
58 self.env_prefix: Literal["uat."] | Literal[""] = "uat." if test else ""
59 if verify_plate:
60 result: dict[str, Any] = self.lookup(reg=verify_plate)
61 if result and result["success"]:
62 log.info("Verified DVLA API lookup using %s, details: %s", verify_plate, result["plate"])
63 else:
64 log.error("DVLA startup verification failed: %s", result)
66 def lookup(self, reg: str) -> dict[str, Any]:
67 if not re.match(self.REG_RE, reg):
68 log.warning(f"DVLA SKIP invalid reg {reg}")
69 return {"reg_match_fail": self.ID, "plate": {}, "success": False}
70 if self.cache_session is None: 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true
71 log.error("Unable to lookup, failed to configure cache session or fallback")
72 return {"lookup_fail": "missing cache", "plate": {}, "success": False}
73 try:
74 with self.cache_session as client:
75 log.debug(f"Fetching DVLA info from API, cache_ttl={self.cache_session.settings.expire_after}")
76 # niquests-cache keys on method, url and headers only, not the body, so the reg goes in the
77 # url fragment to give each plate its own cache entry; fragments are never sent to the server
78 response: niquests.Response = client.post(
79 url=f"https://{self.env_prefix}driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles#{reg.upper()}",
80 headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
81 json={"registrationNumber": reg.upper()},
82 )
83 # cache hits are rebuilt from the stored entry, so have no underlying raw connection response
84 from_cache: bool = response.raw is None
85 created_at: dt.datetime | None = _response_date(response)
86 if from_cache:
87 log.debug("DVLA API cached response, created %s", created_at)
88 if response.status_code == 200:
89 plate: dict[str, Any] = cast("dict[str,Any]", response.json())
90 return {
91 "cache": {
92 "calls": len(response.history) if response.history else 0,
93 "cached": from_cache,
94 "created": created_at.isoformat() if created_at else None,
95 },
96 "plate": plate,
97 "description": f"{plate.get('colour', '').title()} {plate.get('make', '').title()}" if plate else None,
98 "success": True,
99 }
101 body: dict[str, Any] = cast("dict[str,Any]", response.json()) if response.content else {}
102 log.error("DVLA API FAIL: %s", body)
103 return {
104 # DVLA errors come as a list under "errors", AWS API gateway rejections as a "Message"
105 "api_errors": body.get("errors") or ([{"title": body["Message"]}] if "Message" in body else []),
106 "api_status": response.status_code,
107 "plate": {},
108 "success": False,
109 }
110 except Exception as e:
111 log.exception("Failed to fetch DVLA reg data")
112 return {"api_exception": str(e), "plate": {}, "success": False}
115def _response_date(response: niquests.Response) -> dt.datetime | None:
116 """Original response time from the Date header, which is preserved in cached entries."""
117 date_header: str | None = response.headers.get("Date") if response.headers else None
118 if not date_header:
119 return None
120 try:
121 return parsedate_to_datetime(date_header)
122 except (TypeError, ValueError):
123 return None