bookalimo 0.1.4__py3-none-any.whl → 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- bookalimo/__init__.py +17 -24
- bookalimo/_version.py +9 -0
- bookalimo/client.py +310 -0
- bookalimo/config.py +16 -0
- bookalimo/exceptions.py +115 -5
- bookalimo/integrations/__init__.py +1 -0
- bookalimo/integrations/google_places/__init__.py +31 -0
- bookalimo/integrations/google_places/client_async.py +258 -0
- bookalimo/integrations/google_places/client_sync.py +257 -0
- bookalimo/integrations/google_places/common.py +245 -0
- bookalimo/integrations/google_places/proto_adapter.py +224 -0
- bookalimo/{_logging.py → logging.py} +59 -62
- bookalimo/schemas/__init__.py +97 -0
- bookalimo/schemas/base.py +56 -0
- bookalimo/{models.py → schemas/booking.py} +88 -100
- bookalimo/schemas/places/__init__.py +37 -0
- bookalimo/schemas/places/common.py +198 -0
- bookalimo/schemas/places/google.py +596 -0
- bookalimo/schemas/places/place.py +337 -0
- bookalimo/services/__init__.py +11 -0
- bookalimo/services/pricing.py +191 -0
- bookalimo/services/reservations.py +227 -0
- bookalimo/transport/__init__.py +7 -0
- bookalimo/transport/auth.py +41 -0
- bookalimo/transport/base.py +44 -0
- bookalimo/transport/httpx_async.py +230 -0
- bookalimo/transport/httpx_sync.py +230 -0
- bookalimo/transport/retry.py +102 -0
- bookalimo/transport/utils.py +59 -0
- bookalimo-1.0.0.dist-info/METADATA +307 -0
- bookalimo-1.0.0.dist-info/RECORD +35 -0
- bookalimo/_client.py +0 -420
- bookalimo/wrapper.py +0 -444
- bookalimo-0.1.4.dist-info/METADATA +0 -392
- bookalimo-0.1.4.dist-info/RECORD +0 -12
- {bookalimo-0.1.4.dist-info → bookalimo-1.0.0.dist-info}/WHEEL +0 -0
- {bookalimo-0.1.4.dist-info → bookalimo-1.0.0.dist-info}/licenses/LICENSE +0 -0
- {bookalimo-0.1.4.dist-info → bookalimo-1.0.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,596 @@
|
|
1
|
+
import re
|
2
|
+
from typing import Any, Optional, cast
|
3
|
+
|
4
|
+
import pycountry
|
5
|
+
from httpx import QueryParams
|
6
|
+
from pycountry.db import Country
|
7
|
+
from pydantic import (
|
8
|
+
BaseModel,
|
9
|
+
ConfigDict,
|
10
|
+
Field,
|
11
|
+
computed_field,
|
12
|
+
field_validator,
|
13
|
+
model_validator,
|
14
|
+
)
|
15
|
+
from typing_extensions import Self
|
16
|
+
|
17
|
+
from .common import (
|
18
|
+
BASE64URL_36,
|
19
|
+
BCP47,
|
20
|
+
CLDR_REGION_2,
|
21
|
+
PLACE_ID,
|
22
|
+
PLACE_RESOURCE,
|
23
|
+
PLACE_TYPE,
|
24
|
+
LatLng,
|
25
|
+
Viewport,
|
26
|
+
)
|
27
|
+
from .place import Place as GooglePlace
|
28
|
+
|
29
|
+
# ---------- Constants & Enums ----------
|
30
|
+
|
31
|
+
COUNTRY_CODES = {
|
32
|
+
country.alpha_2 for country in cast(list[Country], list(pycountry.countries))
|
33
|
+
}
|
34
|
+
|
35
|
+
|
36
|
+
class PlaceType:
|
37
|
+
"""Place type constants."""
|
38
|
+
|
39
|
+
ADDRESS = "address"
|
40
|
+
AIRPORT = "airport"
|
41
|
+
POI = "poi" # Point of Interest
|
42
|
+
|
43
|
+
|
44
|
+
# ---------- Text Primitives ----------
|
45
|
+
class StringRange(BaseModel):
|
46
|
+
"""Identifies a substring within a given text."""
|
47
|
+
|
48
|
+
model_config = ConfigDict(extra="forbid")
|
49
|
+
|
50
|
+
start_offset: int = Field(
|
51
|
+
default=0, ge=0, description="Zero-based start (inclusive)"
|
52
|
+
)
|
53
|
+
end_offset: int = Field(..., ge=0, description="Zero-based end (exclusive)")
|
54
|
+
|
55
|
+
@model_validator(mode="after")
|
56
|
+
def _validate_order(self) -> Self:
|
57
|
+
if self.start_offset >= self.end_offset:
|
58
|
+
raise ValueError("start_offset must be < end_offset")
|
59
|
+
return self
|
60
|
+
|
61
|
+
|
62
|
+
class FormattableText(BaseModel):
|
63
|
+
"""Text that can be highlighted via `matches` ranges."""
|
64
|
+
|
65
|
+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
66
|
+
|
67
|
+
text: str = Field(..., min_length=1)
|
68
|
+
matches: list[StringRange] = Field(default_factory=list)
|
69
|
+
|
70
|
+
@model_validator(mode="after")
|
71
|
+
def _validate_matches(self) -> Self:
|
72
|
+
n = len(self.text)
|
73
|
+
prev_end = -1
|
74
|
+
for i, r in enumerate(self.matches):
|
75
|
+
if r.end_offset > n:
|
76
|
+
raise ValueError(f"matches[{i}] end_offset exceeds text length ({n})")
|
77
|
+
if r.start_offset < 0:
|
78
|
+
raise ValueError(f"matches[{i}] start_offset must be >= 0")
|
79
|
+
# Enforce strictly increasing, non-overlapping ranges (stronger than spec but safe)
|
80
|
+
if r.start_offset <= prev_end:
|
81
|
+
raise ValueError(
|
82
|
+
"matches must be ordered by increasing, non-overlapping offsets"
|
83
|
+
)
|
84
|
+
prev_end = r.end_offset
|
85
|
+
return self
|
86
|
+
|
87
|
+
|
88
|
+
class StructuredFormat(BaseModel):
|
89
|
+
"""Breakdown of a prediction into main and secondary text."""
|
90
|
+
|
91
|
+
model_config = ConfigDict(extra="forbid")
|
92
|
+
|
93
|
+
main_text: FormattableText
|
94
|
+
secondary_text: FormattableText
|
95
|
+
|
96
|
+
|
97
|
+
# ---------- Geometry Primitives ----------
|
98
|
+
|
99
|
+
|
100
|
+
class Circle(BaseModel):
|
101
|
+
"""google.maps.places_v1.types.Circle (center + radius)."""
|
102
|
+
|
103
|
+
model_config = ConfigDict(extra="forbid")
|
104
|
+
|
105
|
+
center: LatLng
|
106
|
+
radius_meters: float = Field(
|
107
|
+
..., gt=0, description="Strictly positive radius in meters"
|
108
|
+
)
|
109
|
+
|
110
|
+
|
111
|
+
class LocationBias(BaseModel):
|
112
|
+
"""
|
113
|
+
Oneof: exactly one of rectangle or circle must be set.
|
114
|
+
"""
|
115
|
+
|
116
|
+
model_config = ConfigDict(extra="forbid")
|
117
|
+
|
118
|
+
rectangle: Optional[Viewport] = None
|
119
|
+
circle: Optional[Circle] = None
|
120
|
+
|
121
|
+
@model_validator(mode="after")
|
122
|
+
def _validate_oneof(self) -> Self:
|
123
|
+
set_count = sum(x is not None for x in (self.rectangle, self.circle))
|
124
|
+
if set_count != 1:
|
125
|
+
raise ValueError(
|
126
|
+
"Exactly one of {rectangle, circle} must be set for LocationBias"
|
127
|
+
)
|
128
|
+
return self
|
129
|
+
|
130
|
+
|
131
|
+
class LocationRestriction(BaseModel):
|
132
|
+
"""
|
133
|
+
Oneof: exactly one of rectangle or circle must be set.
|
134
|
+
"""
|
135
|
+
|
136
|
+
model_config = ConfigDict(extra="forbid")
|
137
|
+
|
138
|
+
rectangle: Optional[Viewport] = None
|
139
|
+
circle: Optional[Circle] = None
|
140
|
+
|
141
|
+
@model_validator(mode="after")
|
142
|
+
def _validate_oneof(self) -> Self:
|
143
|
+
set_count = sum(x is not None for x in (self.rectangle, self.circle))
|
144
|
+
if set_count != 1:
|
145
|
+
raise ValueError(
|
146
|
+
"Exactly one of {rectangle, circle} must be set for LocationRestriction"
|
147
|
+
)
|
148
|
+
return self
|
149
|
+
|
150
|
+
|
151
|
+
# ---------- Responses ----------
|
152
|
+
|
153
|
+
|
154
|
+
class Place(BaseModel):
|
155
|
+
"""Structured place result from the Google Places API."""
|
156
|
+
|
157
|
+
formatted_address: str = Field(..., description="Full formatted address")
|
158
|
+
lat: float = Field(..., description="Latitude")
|
159
|
+
lng: float = Field(..., description="Longitude")
|
160
|
+
place_type: str = Field(..., description="Type: address, airport, or poi")
|
161
|
+
iata_code: Optional[str] = Field(
|
162
|
+
None, description="IATA airport code if applicable"
|
163
|
+
)
|
164
|
+
google_place: Optional[GooglePlace] = Field(
|
165
|
+
None, description="Raw Google Places API response"
|
166
|
+
)
|
167
|
+
|
168
|
+
@computed_field
|
169
|
+
@property
|
170
|
+
def country_code(self) -> Optional[str]:
|
171
|
+
"""Return ISO 3166-1 alpha-2 country code from the Google Places API response."""
|
172
|
+
return self.extract_country_alpha2(self.google_place)
|
173
|
+
|
174
|
+
@model_validator(mode="after")
|
175
|
+
def validate_place_type(self) -> Self:
|
176
|
+
"""Validate place_type is one of the allowed values."""
|
177
|
+
if self.place_type not in [PlaceType.ADDRESS, PlaceType.AIRPORT, PlaceType.POI]:
|
178
|
+
raise ValueError(f"Invalid place_type: {self.place_type}")
|
179
|
+
return self
|
180
|
+
|
181
|
+
@staticmethod
|
182
|
+
def extract_country_alpha2(google_place: Optional[GooglePlace]) -> Optional[str]:
|
183
|
+
"""Return ISO 3166-1 alpha-2 country code from a Google Places result."""
|
184
|
+
if not google_place:
|
185
|
+
return None
|
186
|
+
|
187
|
+
for comp in google_place.address_components:
|
188
|
+
if "country" in comp.types:
|
189
|
+
code = (comp.short_text or "").upper()
|
190
|
+
return code if code in COUNTRY_CODES and len(code) == 2 else None
|
191
|
+
return None
|
192
|
+
|
193
|
+
|
194
|
+
class AutocompletePlacesResponse(BaseModel):
|
195
|
+
"""Response proto for AutocompletePlaces: ordered suggestions."""
|
196
|
+
|
197
|
+
model_config = ConfigDict(extra="forbid")
|
198
|
+
|
199
|
+
suggestions: list["Suggestion"] = Field(default_factory=list)
|
200
|
+
|
201
|
+
|
202
|
+
class PlacePrediction(BaseModel):
|
203
|
+
"""Prediction result representing a Place."""
|
204
|
+
|
205
|
+
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
206
|
+
|
207
|
+
place: str = Field(..., description="Resource name, e.g., 'places/PLACE_ID'")
|
208
|
+
place_id: str = Field(..., description="Place ID string")
|
209
|
+
text: Optional[FormattableText] = None
|
210
|
+
structured_format: Optional[StructuredFormat] = None
|
211
|
+
types: list[str] = Field(default_factory=list, description="Place types")
|
212
|
+
distance_meters: Optional[int] = Field(default=None, ge=0)
|
213
|
+
|
214
|
+
@field_validator("place")
|
215
|
+
@classmethod
|
216
|
+
def _valid_place_resource(cls, v: str) -> str:
|
217
|
+
if not PLACE_RESOURCE.fullmatch(v):
|
218
|
+
raise ValueError("place must match ^places/[A-Za-z0-9_-]{3,}$")
|
219
|
+
return v
|
220
|
+
|
221
|
+
@field_validator("place_id")
|
222
|
+
@classmethod
|
223
|
+
def _valid_place_id(cls, v: str) -> str:
|
224
|
+
if not PLACE_ID.fullmatch(v):
|
225
|
+
raise ValueError("place_id must be a base64url-like token of length >= 10")
|
226
|
+
return v
|
227
|
+
|
228
|
+
@field_validator("types")
|
229
|
+
@classmethod
|
230
|
+
def _validate_types(cls, v: list[str]) -> list[str]:
|
231
|
+
cleaned: list[str] = []
|
232
|
+
seen = set()
|
233
|
+
for raw in v:
|
234
|
+
t = raw.strip()
|
235
|
+
if not t:
|
236
|
+
raise ValueError("types cannot contain empty strings")
|
237
|
+
if not PLACE_TYPE.fullmatch(t):
|
238
|
+
raise ValueError(
|
239
|
+
f"Invalid place type '{t}'. Use lowercase letters, digits, and underscores."
|
240
|
+
)
|
241
|
+
if t not in seen:
|
242
|
+
cleaned.append(t)
|
243
|
+
seen.add(t)
|
244
|
+
return cleaned
|
245
|
+
|
246
|
+
@model_validator(mode="after")
|
247
|
+
def _at_least_one_text_representation(self) -> Self:
|
248
|
+
if self.text is None and self.structured_format is None:
|
249
|
+
raise ValueError(
|
250
|
+
"At least one of {text, structured_format} must be provided"
|
251
|
+
)
|
252
|
+
return self
|
253
|
+
|
254
|
+
|
255
|
+
class QueryPrediction(BaseModel):
|
256
|
+
"""Prediction result representing a query (not a Place)."""
|
257
|
+
|
258
|
+
model_config = ConfigDict(extra="forbid")
|
259
|
+
|
260
|
+
text: Optional[FormattableText] = None
|
261
|
+
structured_format: Optional[StructuredFormat] = None
|
262
|
+
|
263
|
+
@model_validator(mode="after")
|
264
|
+
def _at_least_one_text_representation(self) -> Self:
|
265
|
+
if self.text is None and self.structured_format is None:
|
266
|
+
raise ValueError(
|
267
|
+
"At least one of {text, structured_format} must be provided"
|
268
|
+
)
|
269
|
+
return self
|
270
|
+
|
271
|
+
|
272
|
+
class Suggestion(BaseModel):
|
273
|
+
"""
|
274
|
+
Oneof 'kind': exactly one of place_prediction or query_prediction must be set.
|
275
|
+
"""
|
276
|
+
|
277
|
+
model_config = ConfigDict(extra="forbid")
|
278
|
+
|
279
|
+
place_prediction: Optional[PlacePrediction] = None
|
280
|
+
query_prediction: Optional[QueryPrediction] = None
|
281
|
+
|
282
|
+
@model_validator(mode="after")
|
283
|
+
def _validate_oneof(self) -> Self:
|
284
|
+
count = sum(
|
285
|
+
x is not None for x in (self.place_prediction, self.query_prediction)
|
286
|
+
)
|
287
|
+
if count != 1:
|
288
|
+
raise ValueError(
|
289
|
+
"Exactly one of {place_prediction, query_prediction} must be set"
|
290
|
+
)
|
291
|
+
return self
|
292
|
+
|
293
|
+
|
294
|
+
# ---------- Requests ----------
|
295
|
+
|
296
|
+
|
297
|
+
class GetPlaceRequest(BaseModel):
|
298
|
+
"""
|
299
|
+
Request for fetching a Place by resource name 'places/{place_id}'.
|
300
|
+
|
301
|
+
- name: required, must match ^places/[A-Za-z0-9_-]{10,}$
|
302
|
+
- language_code: optional BCP-47 tag (e.g., 'en', 'en-US', 'zh-Hant')
|
303
|
+
- region_code: optional CLDR region code (2 letters, uppercase). 3-digit codes not supported.
|
304
|
+
- session_token: optional base64url (URL/filename-safe) up to 36 chars.
|
305
|
+
"""
|
306
|
+
|
307
|
+
model_config = ConfigDict(
|
308
|
+
extra="forbid", str_strip_whitespace=True, populate_by_name=True
|
309
|
+
)
|
310
|
+
|
311
|
+
name: str = Field(..., description="Resource name in the form 'places/{place_id}'.")
|
312
|
+
language_code: Optional[str] = Field(
|
313
|
+
default=None,
|
314
|
+
description="Preferred language (BCP-47). If unavailable, backend defaults apply.",
|
315
|
+
)
|
316
|
+
region_code: Optional[str] = Field(
|
317
|
+
default=None,
|
318
|
+
description="CLDR region code (2 letters, e.g., 'US'). 3-digit codes not supported.",
|
319
|
+
)
|
320
|
+
session_token: Optional[str] = Field(
|
321
|
+
default=None,
|
322
|
+
description="Base64url token (URL/filename-safe), length 1–36, for Autocomplete billing sessions.",
|
323
|
+
)
|
324
|
+
|
325
|
+
# ---- Field validators ----
|
326
|
+
@field_validator("name")
|
327
|
+
@classmethod
|
328
|
+
def _validate_name(cls, v: str) -> str:
|
329
|
+
if not PLACE_RESOURCE.fullmatch(v):
|
330
|
+
raise ValueError(
|
331
|
+
"name must be in the form 'places/{place_id}' with a base64url-like place_id (>=10 chars)."
|
332
|
+
)
|
333
|
+
return v
|
334
|
+
|
335
|
+
@field_validator("language_code")
|
336
|
+
@classmethod
|
337
|
+
def _validate_language_code(cls, v: Optional[str]) -> Optional[str]:
|
338
|
+
if v is None:
|
339
|
+
return v
|
340
|
+
if not BCP47.match(v):
|
341
|
+
raise ValueError(
|
342
|
+
"language_code must be a valid BCP-47 tag (e.g., 'en', 'en-US', 'zh-Hant')."
|
343
|
+
)
|
344
|
+
return v
|
345
|
+
|
346
|
+
@field_validator("region_code")
|
347
|
+
@classmethod
|
348
|
+
def _validate_region_code(cls, v: Optional[str]) -> Optional[str]:
|
349
|
+
if v is None:
|
350
|
+
return v
|
351
|
+
v2 = v.upper()
|
352
|
+
if not CLDR_REGION_2.fullmatch(v2):
|
353
|
+
raise ValueError(
|
354
|
+
"region_code must be a two-letter CLDR region code (e.g., 'US', 'GB')."
|
355
|
+
)
|
356
|
+
return v2
|
357
|
+
|
358
|
+
@field_validator("session_token")
|
359
|
+
@classmethod
|
360
|
+
def _validate_session_token(cls, v: Optional[str]) -> Optional[str]:
|
361
|
+
if v is None:
|
362
|
+
return v
|
363
|
+
if not BASE64URL_36.fullmatch(v):
|
364
|
+
raise ValueError(
|
365
|
+
"session_token must be base64url (A–Z a–z 0–9 _ -), length 1–36."
|
366
|
+
)
|
367
|
+
return v
|
368
|
+
|
369
|
+
# ---- Convenience (not part of the wire schema) ----
|
370
|
+
@property
|
371
|
+
def place_id(self) -> str:
|
372
|
+
"""Extract the {place_id} from 'places/{place_id}'."""
|
373
|
+
return self.name.split("/", 1)[1]
|
374
|
+
|
375
|
+
|
376
|
+
class AutocompletePlacesRequest(BaseModel):
|
377
|
+
"""
|
378
|
+
Pydantic v2 model for AutocompletePlacesRequest with rich validations.
|
379
|
+
"""
|
380
|
+
|
381
|
+
model_config = ConfigDict(
|
382
|
+
extra="forbid", str_strip_whitespace=True, populate_by_name=True
|
383
|
+
)
|
384
|
+
|
385
|
+
# Required search text
|
386
|
+
input: str = Field(
|
387
|
+
..., min_length=1, description="The text string on which to search."
|
388
|
+
)
|
389
|
+
|
390
|
+
# Mutually exclusive geospatial hints (top-level 'at most one' rule)
|
391
|
+
location_bias: Optional[LocationBias] = None
|
392
|
+
location_restriction: Optional[LocationRestriction] = None
|
393
|
+
|
394
|
+
# Place types (<= 5). Either a list of normal types OR exactly one of the special tokens.
|
395
|
+
included_primary_types: list[str] = Field(default_factory=list)
|
396
|
+
|
397
|
+
# Region filters (<= 15) as CLDR two-letter codes (uppercased, de-duplicated).
|
398
|
+
included_region_codes: list[str] = Field(default_factory=list)
|
399
|
+
|
400
|
+
# Localization
|
401
|
+
language_code: str = Field(
|
402
|
+
default="en-US", description="BCP-47 language tag, default en-US."
|
403
|
+
)
|
404
|
+
region_code: Optional[str] = Field(
|
405
|
+
default=None, description="CLDR region code (2 letters, e.g., 'US')."
|
406
|
+
)
|
407
|
+
|
408
|
+
# Distance origin (if present, distance is returned)
|
409
|
+
origin: Optional[LatLng] = None
|
410
|
+
|
411
|
+
# Cursor position in `input`; if omitted, defaults to len(input)
|
412
|
+
input_offset: Optional[int] = None
|
413
|
+
|
414
|
+
# Flags
|
415
|
+
include_query_predictions: bool = False
|
416
|
+
include_pure_service_area_businesses: bool = False
|
417
|
+
|
418
|
+
# Session token: URL/filename safe base64url, <= 36 ASCII chars
|
419
|
+
session_token: Optional[str] = None
|
420
|
+
|
421
|
+
# -------------------- Field-level validations & normalization --------------------
|
422
|
+
|
423
|
+
@field_validator("included_primary_types")
|
424
|
+
@classmethod
|
425
|
+
def _validate_primary_types(cls, v: list[str]) -> list[str]:
|
426
|
+
# Enforce <= 5, no empties, trim & dedupe (preserving order)
|
427
|
+
if len(v) > 5:
|
428
|
+
raise ValueError("included_primary_types can contain at most 5 values")
|
429
|
+
cleaned: list[str] = []
|
430
|
+
seen = set()
|
431
|
+
for raw in v:
|
432
|
+
t = raw.strip()
|
433
|
+
if not t:
|
434
|
+
raise ValueError("included_primary_types cannot contain empty strings")
|
435
|
+
if t not in seen:
|
436
|
+
cleaned.append(t)
|
437
|
+
seen.add(t)
|
438
|
+
|
439
|
+
# Special tokens constraint: allow exactly one item when using "(regions)" or "(cities)"
|
440
|
+
specials = {"(regions)", "(cities)"}
|
441
|
+
if any(t in specials for t in cleaned):
|
442
|
+
if len(cleaned) != 1 or cleaned[0] not in specials:
|
443
|
+
raise ValueError(
|
444
|
+
"When using special tokens, included_primary_types must be exactly one of '(regions)' or '(cities)'."
|
445
|
+
)
|
446
|
+
return cleaned
|
447
|
+
|
448
|
+
# Otherwise validate normal place-type tokens format (lowercase, digits, underscores)
|
449
|
+
for t in cleaned:
|
450
|
+
if not PLACE_TYPE.match(t):
|
451
|
+
raise ValueError(
|
452
|
+
f"Invalid place type '{t}'. Use lowercase letters, digits, and underscores (e.g., 'gas_station')."
|
453
|
+
)
|
454
|
+
return cleaned
|
455
|
+
|
456
|
+
@field_validator("included_region_codes")
|
457
|
+
@classmethod
|
458
|
+
def _validate_region_codes(cls, v: list[str]) -> list[str]:
|
459
|
+
if len(v) > 15:
|
460
|
+
raise ValueError("included_region_codes can contain at most 15 values")
|
461
|
+
out: list[str] = []
|
462
|
+
seen = set()
|
463
|
+
for raw in v:
|
464
|
+
code = raw.strip().upper()
|
465
|
+
if not re.fullmatch(r"[A-Z]{2}", code):
|
466
|
+
raise ValueError(
|
467
|
+
f"Region code '{raw}' must be a two-letter CLDR region code (e.g., 'US', 'GB')."
|
468
|
+
)
|
469
|
+
if code not in seen:
|
470
|
+
out.append(code)
|
471
|
+
seen.add(code)
|
472
|
+
return out
|
473
|
+
|
474
|
+
@field_validator("language_code")
|
475
|
+
@classmethod
|
476
|
+
def _validate_language_code(cls, v: str) -> str:
|
477
|
+
if not BCP47.match(v):
|
478
|
+
raise ValueError(
|
479
|
+
"language_code must be a valid BCP-47 tag (e.g., 'en', 'en-US', 'zh-Hant')."
|
480
|
+
)
|
481
|
+
return v
|
482
|
+
|
483
|
+
@field_validator("region_code")
|
484
|
+
@classmethod
|
485
|
+
def _validate_region_code(cls, v: Optional[str]) -> Optional[str]:
|
486
|
+
if v is None:
|
487
|
+
return v
|
488
|
+
v2 = v.strip().upper()
|
489
|
+
if not re.fullmatch(r"[A-Z]{2}", v2):
|
490
|
+
raise ValueError(
|
491
|
+
"region_code must be a two-letter CLDR region code (e.g., 'US', 'GB')."
|
492
|
+
)
|
493
|
+
return v2
|
494
|
+
|
495
|
+
@field_validator("session_token")
|
496
|
+
@classmethod
|
497
|
+
def _validate_session_token(cls, v: Optional[str]) -> Optional[str]:
|
498
|
+
if v is None:
|
499
|
+
return v
|
500
|
+
# URL/filename-safe base64 (base64url) up to 36 chars: A–Z a–z 0–9 _ -
|
501
|
+
if not BASE64URL_36.fullmatch(v):
|
502
|
+
raise ValueError(
|
503
|
+
"session_token must be URL/filename-safe base64 (base64url) of length 1–36 using [A-Za-z0-9_-]."
|
504
|
+
)
|
505
|
+
return v
|
506
|
+
|
507
|
+
@field_validator("input")
|
508
|
+
@classmethod
|
509
|
+
def _validate_input_nonempty(cls, v: str) -> str:
|
510
|
+
if len(v) == 0:
|
511
|
+
raise ValueError("input cannot be empty")
|
512
|
+
return v
|
513
|
+
|
514
|
+
@field_validator("input_offset")
|
515
|
+
@classmethod
|
516
|
+
def _validate_input_offset(cls, v: Optional[int], info: Any) -> Optional[int]:
|
517
|
+
# Can't compare to input length here (other fields not guaranteed yet),
|
518
|
+
# so we only enforce non-negative. Range is finished in the model_validator below.
|
519
|
+
if v is not None and v < 0:
|
520
|
+
raise ValueError("input_offset must be a non-negative integer")
|
521
|
+
return v
|
522
|
+
|
523
|
+
# -------------------- Cross-field validations --------------------
|
524
|
+
|
525
|
+
@model_validator(mode="after")
|
526
|
+
def _validate_cross_fields(self) -> Self:
|
527
|
+
# Top-level exclusivity: at most one of location_bias / location_restriction
|
528
|
+
if self.location_bias is not None and self.location_restriction is not None:
|
529
|
+
raise ValueError(
|
530
|
+
"At most one of {location_bias, location_restriction} may be set."
|
531
|
+
)
|
532
|
+
|
533
|
+
# Default input_offset to len(input) if omitted; else enforce range
|
534
|
+
if self.input_offset is None:
|
535
|
+
object.__setattr__(self, "input_offset", len(self.input))
|
536
|
+
else:
|
537
|
+
if self.input_offset > len(self.input):
|
538
|
+
raise ValueError(
|
539
|
+
"input_offset cannot be greater than the length of input"
|
540
|
+
)
|
541
|
+
|
542
|
+
return self
|
543
|
+
|
544
|
+
|
545
|
+
class GeocodingRequest(BaseModel):
|
546
|
+
"""
|
547
|
+
Pydantic model for validating and building Geocoding API query parameters.
|
548
|
+
This model is not for a JSON request body, but for constructing a URL.
|
549
|
+
"""
|
550
|
+
|
551
|
+
address: Optional[str] = Field(
|
552
|
+
default=None,
|
553
|
+
description="The street address or plus code that you want to geocode.",
|
554
|
+
)
|
555
|
+
place_id: Optional[str] = Field(
|
556
|
+
default=None,
|
557
|
+
description="The place ID of the place for which you wish to obtain the human-readable address.",
|
558
|
+
)
|
559
|
+
language: Optional[str] = Field(
|
560
|
+
default=None, description="The language in which to return results."
|
561
|
+
)
|
562
|
+
region: Optional[str] = Field(
|
563
|
+
default=None, description="The region code (ccTLD) to bias results."
|
564
|
+
)
|
565
|
+
|
566
|
+
@model_validator(mode="before")
|
567
|
+
@classmethod
|
568
|
+
def check_required_params(cls, data: Any) -> Any:
|
569
|
+
"""Ensures that either 'address', 'place_id', or 'components' is provided."""
|
570
|
+
if isinstance(data, dict):
|
571
|
+
if not any(
|
572
|
+
[data.get("address"), data.get("place_id"), data.get("components")]
|
573
|
+
):
|
574
|
+
raise ValueError(
|
575
|
+
"You must specify either 'address', 'place_id', or 'components'."
|
576
|
+
)
|
577
|
+
return data
|
578
|
+
|
579
|
+
def to_query_params(self) -> QueryParams:
|
580
|
+
"""
|
581
|
+
Serializes the model fields into a dictionary suitable for URL query parameters.
|
582
|
+
"""
|
583
|
+
params = QueryParams()
|
584
|
+
if self.address:
|
585
|
+
params = params.add("address", self.address)
|
586
|
+
|
587
|
+
if self.place_id:
|
588
|
+
params = params.add("place_id", self.place_id)
|
589
|
+
|
590
|
+
if self.language:
|
591
|
+
params = params.add("language", self.language)
|
592
|
+
|
593
|
+
if self.region:
|
594
|
+
params = params.add("region", self.region)
|
595
|
+
|
596
|
+
return params
|