train-travel 0.0.7__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.
Files changed (62) hide show
  1. train_travel/__init__.py +17 -0
  2. train_travel/_hooks/__init__.py +6 -0
  3. train_travel/_hooks/oauth2scopes.py +16 -0
  4. train_travel/_hooks/registration.py +13 -0
  5. train_travel/_hooks/sdkhooks.py +76 -0
  6. train_travel/_hooks/types.py +112 -0
  7. train_travel/_version.py +15 -0
  8. train_travel/basesdk.py +388 -0
  9. train_travel/bookings.py +1190 -0
  10. train_travel/errors/__init__.py +63 -0
  11. train_travel/errors/no_response_error.py +17 -0
  12. train_travel/errors/responsevalidationerror.py +27 -0
  13. train_travel/errors/traintraveldefaulterror.py +40 -0
  14. train_travel/errors/traintravelerror.py +30 -0
  15. train_travel/httpclient.py +125 -0
  16. train_travel/models/__init__.py +416 -0
  17. train_travel/models/booking.py +59 -0
  18. train_travel/models/booking_input.py +52 -0
  19. train_travel/models/bookingpayment.py +221 -0
  20. train_travel/models/create_booking_paymentop.py +269 -0
  21. train_travel/models/create_booking_rawop.py +144 -0
  22. train_travel/models/create_bookingop.py +144 -0
  23. train_travel/models/delete_bookingop.py +30 -0
  24. train_travel/models/get_bookingop.py +159 -0
  25. train_travel/models/get_bookingsop.py +198 -0
  26. train_travel/models/get_stationsop.py +230 -0
  27. train_travel/models/get_tripsop.py +324 -0
  28. train_travel/models/links_booking.py +35 -0
  29. train_travel/models/links_self.py +36 -0
  30. train_travel/models/new_bookingop.py +92 -0
  31. train_travel/models/security.py +39 -0
  32. train_travel/models/station.py +57 -0
  33. train_travel/models/trip.py +90 -0
  34. train_travel/payments.py +262 -0
  35. train_travel/py.typed +1 -0
  36. train_travel/sdk.py +213 -0
  37. train_travel/sdkconfiguration.py +51 -0
  38. train_travel/stations.py +284 -0
  39. train_travel/trips.py +291 -0
  40. train_travel/types/__init__.py +21 -0
  41. train_travel/types/basemodel.py +77 -0
  42. train_travel/utils/__init__.py +206 -0
  43. train_travel/utils/annotations.py +79 -0
  44. train_travel/utils/datetimes.py +23 -0
  45. train_travel/utils/enums.py +134 -0
  46. train_travel/utils/eventstreaming.py +248 -0
  47. train_travel/utils/forms.py +234 -0
  48. train_travel/utils/headers.py +136 -0
  49. train_travel/utils/logger.py +27 -0
  50. train_travel/utils/metadata.py +118 -0
  51. train_travel/utils/queryparams.py +217 -0
  52. train_travel/utils/requestbodies.py +66 -0
  53. train_travel/utils/retries.py +281 -0
  54. train_travel/utils/security.py +192 -0
  55. train_travel/utils/serializers.py +229 -0
  56. train_travel/utils/unmarshal_json_response.py +38 -0
  57. train_travel/utils/url.py +155 -0
  58. train_travel/utils/values.py +137 -0
  59. train_travel-0.0.7.dist-info/METADATA +567 -0
  60. train_travel-0.0.7.dist-info/RECORD +62 -0
  61. train_travel-0.0.7.dist-info/WHEEL +5 -0
  62. train_travel-0.0.7.dist-info/top_level.txt +1 -0
@@ -0,0 +1,281 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import asyncio
4
+ import random
5
+ import time
6
+ from datetime import datetime
7
+ from email.utils import parsedate_to_datetime
8
+ from typing import List, Optional
9
+
10
+ import httpx
11
+
12
+
13
+ class BackoffStrategy:
14
+ initial_interval: int
15
+ max_interval: int
16
+ exponent: float
17
+ max_elapsed_time: int
18
+
19
+ def __init__(
20
+ self,
21
+ initial_interval: int,
22
+ max_interval: int,
23
+ exponent: float,
24
+ max_elapsed_time: int,
25
+ ):
26
+ self.initial_interval = initial_interval
27
+ self.max_interval = max_interval
28
+ self.exponent = exponent
29
+ self.max_elapsed_time = max_elapsed_time
30
+
31
+
32
+ class RetryConfig:
33
+ strategy: str
34
+ backoff: BackoffStrategy
35
+ retry_connection_errors: bool
36
+
37
+ def __init__(
38
+ self, strategy: str, backoff: BackoffStrategy, retry_connection_errors: bool
39
+ ):
40
+ self.strategy = strategy
41
+ self.backoff = backoff
42
+ self.retry_connection_errors = retry_connection_errors
43
+
44
+
45
+ class Retries:
46
+ config: RetryConfig
47
+ status_codes: List[str]
48
+
49
+ def __init__(self, config: RetryConfig, status_codes: List[str]):
50
+ self.config = config
51
+ self.status_codes = status_codes
52
+
53
+
54
+ class TemporaryError(Exception):
55
+ response: httpx.Response
56
+ retry_after: Optional[int]
57
+
58
+ def __init__(self, response: httpx.Response):
59
+ self.response = response
60
+ self.retry_after = _parse_retry_after_header(response)
61
+
62
+
63
+ class PermanentError(Exception):
64
+ inner: Exception
65
+
66
+ def __init__(self, inner: Exception):
67
+ self.inner = inner
68
+
69
+
70
+ def _parse_retry_after_header(response: httpx.Response) -> Optional[int]:
71
+ """Parse Retry-After header from response.
72
+
73
+ Returns:
74
+ Retry interval in milliseconds, or None if header is missing or invalid.
75
+ """
76
+ retry_after_header = response.headers.get("retry-after")
77
+ if not retry_after_header:
78
+ return None
79
+
80
+ try:
81
+ seconds = float(retry_after_header)
82
+ return round(seconds * 1000)
83
+ except ValueError:
84
+ pass
85
+
86
+ try:
87
+ retry_date = parsedate_to_datetime(retry_after_header)
88
+ delta = (retry_date - datetime.now(retry_date.tzinfo)).total_seconds()
89
+ return round(max(0, delta) * 1000)
90
+ except (ValueError, TypeError):
91
+ pass
92
+
93
+ return None
94
+
95
+
96
+ def _get_sleep_interval(
97
+ exception: Exception,
98
+ initial_interval: int,
99
+ max_interval: int,
100
+ exponent: float,
101
+ retries: int,
102
+ ) -> float:
103
+ """Get sleep interval for retry with exponential backoff.
104
+
105
+ Args:
106
+ exception: The exception that triggered the retry.
107
+ initial_interval: Initial retry interval in milliseconds.
108
+ max_interval: Maximum retry interval in milliseconds.
109
+ exponent: Base for exponential backoff calculation.
110
+ retries: Current retry attempt count.
111
+
112
+ Returns:
113
+ Sleep interval in seconds.
114
+ """
115
+ if (
116
+ isinstance(exception, TemporaryError)
117
+ and exception.retry_after is not None
118
+ and exception.retry_after > 0
119
+ ):
120
+ return exception.retry_after / 1000
121
+
122
+ sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1)
123
+ return min(sleep, max_interval / 1000)
124
+
125
+
126
+ def retry(func, retries: Retries):
127
+ if retries.config.strategy == "backoff":
128
+
129
+ def do_request() -> httpx.Response:
130
+ res: httpx.Response
131
+ try:
132
+ res = func()
133
+
134
+ for code in retries.status_codes:
135
+ if "X" in code.upper():
136
+ code_range = int(code[0])
137
+
138
+ status_major = res.status_code / 100
139
+
140
+ if code_range <= status_major < code_range + 1:
141
+ raise TemporaryError(res)
142
+ else:
143
+ parsed_code = int(code)
144
+
145
+ if res.status_code == parsed_code:
146
+ raise TemporaryError(res)
147
+ except httpx.ConnectError as exception:
148
+ if retries.config.retry_connection_errors:
149
+ raise
150
+
151
+ raise PermanentError(exception) from exception
152
+ except httpx.TimeoutException as exception:
153
+ if retries.config.retry_connection_errors:
154
+ raise
155
+
156
+ raise PermanentError(exception) from exception
157
+ except TemporaryError:
158
+ raise
159
+ except Exception as exception:
160
+ raise PermanentError(exception) from exception
161
+
162
+ return res
163
+
164
+ return retry_with_backoff(
165
+ do_request,
166
+ retries.config.backoff.initial_interval,
167
+ retries.config.backoff.max_interval,
168
+ retries.config.backoff.exponent,
169
+ retries.config.backoff.max_elapsed_time,
170
+ )
171
+
172
+ return func()
173
+
174
+
175
+ async def retry_async(func, retries: Retries):
176
+ if retries.config.strategy == "backoff":
177
+
178
+ async def do_request() -> httpx.Response:
179
+ res: httpx.Response
180
+ try:
181
+ res = await func()
182
+
183
+ for code in retries.status_codes:
184
+ if "X" in code.upper():
185
+ code_range = int(code[0])
186
+
187
+ status_major = res.status_code / 100
188
+
189
+ if code_range <= status_major < code_range + 1:
190
+ raise TemporaryError(res)
191
+ else:
192
+ parsed_code = int(code)
193
+
194
+ if res.status_code == parsed_code:
195
+ raise TemporaryError(res)
196
+ except httpx.ConnectError as exception:
197
+ if retries.config.retry_connection_errors:
198
+ raise
199
+
200
+ raise PermanentError(exception) from exception
201
+ except httpx.TimeoutException as exception:
202
+ if retries.config.retry_connection_errors:
203
+ raise
204
+
205
+ raise PermanentError(exception) from exception
206
+ except TemporaryError:
207
+ raise
208
+ except Exception as exception:
209
+ raise PermanentError(exception) from exception
210
+
211
+ return res
212
+
213
+ return await retry_with_backoff_async(
214
+ do_request,
215
+ retries.config.backoff.initial_interval,
216
+ retries.config.backoff.max_interval,
217
+ retries.config.backoff.exponent,
218
+ retries.config.backoff.max_elapsed_time,
219
+ )
220
+
221
+ return await func()
222
+
223
+
224
+ def retry_with_backoff(
225
+ func,
226
+ initial_interval=500,
227
+ max_interval=60000,
228
+ exponent=1.5,
229
+ max_elapsed_time=3600000,
230
+ ):
231
+ start = round(time.time() * 1000)
232
+ retries = 0
233
+
234
+ while True:
235
+ try:
236
+ return func()
237
+ except PermanentError as exception:
238
+ raise exception.inner
239
+ except Exception as exception: # pylint: disable=broad-exception-caught
240
+ now = round(time.time() * 1000)
241
+ if now - start > max_elapsed_time:
242
+ if isinstance(exception, TemporaryError):
243
+ return exception.response
244
+
245
+ raise
246
+
247
+ sleep = _get_sleep_interval(
248
+ exception, initial_interval, max_interval, exponent, retries
249
+ )
250
+ time.sleep(sleep)
251
+ retries += 1
252
+
253
+
254
+ async def retry_with_backoff_async(
255
+ func,
256
+ initial_interval=500,
257
+ max_interval=60000,
258
+ exponent=1.5,
259
+ max_elapsed_time=3600000,
260
+ ):
261
+ start = round(time.time() * 1000)
262
+ retries = 0
263
+
264
+ while True:
265
+ try:
266
+ return await func()
267
+ except PermanentError as exception:
268
+ raise exception.inner
269
+ except Exception as exception: # pylint: disable=broad-exception-caught
270
+ now = round(time.time() * 1000)
271
+ if now - start > max_elapsed_time:
272
+ if isinstance(exception, TemporaryError):
273
+ return exception.response
274
+
275
+ raise
276
+
277
+ sleep = _get_sleep_interval(
278
+ exception, initial_interval, max_interval, exponent, retries
279
+ )
280
+ await asyncio.sleep(sleep)
281
+ retries += 1
@@ -0,0 +1,192 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import base64
4
+
5
+ from typing import (
6
+ Any,
7
+ Dict,
8
+ List,
9
+ Optional,
10
+ Tuple,
11
+ )
12
+ from pydantic import BaseModel
13
+ from pydantic.fields import FieldInfo
14
+
15
+ from .metadata import (
16
+ SecurityMetadata,
17
+ find_field_metadata,
18
+ )
19
+ import os
20
+
21
+
22
+ def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, List[str]]]:
23
+ headers: Dict[str, str] = {}
24
+ query_params: Dict[str, List[str]] = {}
25
+
26
+ if security is None:
27
+ return headers, query_params
28
+
29
+ if not isinstance(security, BaseModel):
30
+ raise TypeError("security must be a pydantic model")
31
+
32
+ sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields
33
+ for name in sec_fields:
34
+ sec_field = sec_fields[name]
35
+
36
+ value = getattr(security, name)
37
+ if value is None:
38
+ continue
39
+
40
+ metadata = find_field_metadata(sec_field, SecurityMetadata)
41
+ if metadata is None:
42
+ continue
43
+ if metadata.option:
44
+ _parse_security_option(headers, query_params, value)
45
+ return headers, query_params
46
+ if metadata.scheme:
47
+ # Special case for basic auth or custom auth which could be a flattened model
48
+ if metadata.sub_type in ["basic", "custom"] and not isinstance(
49
+ value, BaseModel
50
+ ):
51
+ _parse_security_scheme(headers, query_params, metadata, name, security)
52
+ else:
53
+ _parse_security_scheme(headers, query_params, metadata, name, value)
54
+
55
+ return headers, query_params
56
+
57
+
58
+ def get_security_from_env(security: Any, security_class: Any) -> Optional[BaseModel]:
59
+ if security is not None:
60
+ return security
61
+
62
+ if not issubclass(security_class, BaseModel):
63
+ raise TypeError("security_class must be a pydantic model class")
64
+
65
+ security_dict: Any = {}
66
+
67
+ if os.getenv("TRAINTRAVEL_O_AUTH2"):
68
+ security_dict["o_auth2"] = os.getenv("TRAINTRAVEL_O_AUTH2")
69
+
70
+ return security_class(**security_dict) if security_dict else None
71
+
72
+
73
+ def _parse_security_option(
74
+ headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any
75
+ ):
76
+ if not isinstance(option, BaseModel):
77
+ raise TypeError("security option must be a pydantic model")
78
+
79
+ opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields
80
+ for name in opt_fields:
81
+ opt_field = opt_fields[name]
82
+
83
+ metadata = find_field_metadata(opt_field, SecurityMetadata)
84
+ if metadata is None or not metadata.scheme:
85
+ continue
86
+ _parse_security_scheme(
87
+ headers, query_params, metadata, name, getattr(option, name)
88
+ )
89
+
90
+
91
+ def _parse_security_scheme(
92
+ headers: Dict[str, str],
93
+ query_params: Dict[str, List[str]],
94
+ scheme_metadata: SecurityMetadata,
95
+ field_name: str,
96
+ scheme: Any,
97
+ ):
98
+ scheme_type = scheme_metadata.scheme_type
99
+ sub_type = scheme_metadata.sub_type
100
+
101
+ if isinstance(scheme, BaseModel):
102
+ if scheme_type == "http":
103
+ if sub_type == "basic":
104
+ _parse_basic_auth_scheme(headers, scheme)
105
+ return
106
+ if sub_type == "custom":
107
+ return
108
+
109
+ scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
110
+ for name in scheme_fields:
111
+ scheme_field = scheme_fields[name]
112
+
113
+ metadata = find_field_metadata(scheme_field, SecurityMetadata)
114
+ if metadata is None or metadata.field_name is None:
115
+ continue
116
+
117
+ value = getattr(scheme, name)
118
+
119
+ _parse_security_scheme_value(
120
+ headers, query_params, scheme_metadata, metadata, name, value
121
+ )
122
+ else:
123
+ _parse_security_scheme_value(
124
+ headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme
125
+ )
126
+
127
+
128
+ def _parse_security_scheme_value(
129
+ headers: Dict[str, str],
130
+ query_params: Dict[str, List[str]],
131
+ scheme_metadata: SecurityMetadata,
132
+ security_metadata: SecurityMetadata,
133
+ field_name: str,
134
+ value: Any,
135
+ ):
136
+ scheme_type = scheme_metadata.scheme_type
137
+ sub_type = scheme_metadata.sub_type
138
+
139
+ header_name = security_metadata.get_field_name(field_name)
140
+
141
+ if scheme_type == "apiKey":
142
+ if sub_type == "header":
143
+ headers[header_name] = value
144
+ elif sub_type == "query":
145
+ query_params[header_name] = [value]
146
+ else:
147
+ raise ValueError("sub type {sub_type} not supported")
148
+ elif scheme_type == "openIdConnect":
149
+ headers[header_name] = _apply_bearer(value)
150
+ elif scheme_type == "oauth2":
151
+ if sub_type != "client_credentials":
152
+ headers[header_name] = _apply_bearer(value)
153
+ elif scheme_type == "http":
154
+ if sub_type == "bearer":
155
+ headers[header_name] = _apply_bearer(value)
156
+ elif sub_type == "custom":
157
+ return
158
+ else:
159
+ raise ValueError("sub type {sub_type} not supported")
160
+ else:
161
+ raise ValueError("scheme type {scheme_type} not supported")
162
+
163
+
164
+ def _apply_bearer(token: str) -> str:
165
+ return token.lower().startswith("bearer ") and token or f"Bearer {token}"
166
+
167
+
168
+ def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any):
169
+ username = ""
170
+ password = ""
171
+
172
+ if not isinstance(scheme, BaseModel):
173
+ raise TypeError("basic auth scheme must be a pydantic model")
174
+
175
+ scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
176
+ for name in scheme_fields:
177
+ scheme_field = scheme_fields[name]
178
+
179
+ metadata = find_field_metadata(scheme_field, SecurityMetadata)
180
+ if metadata is None or metadata.field_name is None:
181
+ continue
182
+
183
+ field_name = metadata.field_name
184
+ value = getattr(scheme, name)
185
+
186
+ if field_name == "username":
187
+ username = value
188
+ if field_name == "password":
189
+ password = value
190
+
191
+ data = f"{username}:{password}".encode()
192
+ headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}"
@@ -0,0 +1,229 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from decimal import Decimal
4
+ import functools
5
+ import json
6
+ import typing
7
+ from typing import Any, Dict, List, Tuple, Union, get_args
8
+ import typing_extensions
9
+ from typing_extensions import get_origin
10
+
11
+ import httpx
12
+ from pydantic import ConfigDict, create_model
13
+ from pydantic_core import from_json
14
+
15
+ from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset
16
+
17
+
18
+ def serialize_decimal(as_str: bool):
19
+ def serialize(d):
20
+ # Optional[T] is a Union[T, None]
21
+ if is_union(type(d)) and type(None) in get_args(type(d)) and d is None:
22
+ return None
23
+ if isinstance(d, Unset):
24
+ return d
25
+
26
+ if not isinstance(d, Decimal):
27
+ raise ValueError("Expected Decimal object")
28
+
29
+ return str(d) if as_str else float(d)
30
+
31
+ return serialize
32
+
33
+
34
+ def validate_decimal(d):
35
+ if d is None:
36
+ return None
37
+
38
+ if isinstance(d, (Decimal, Unset)):
39
+ return d
40
+
41
+ if not isinstance(d, (str, int, float)):
42
+ raise ValueError("Expected string, int or float")
43
+
44
+ return Decimal(str(d))
45
+
46
+
47
+ def serialize_float(as_str: bool):
48
+ def serialize(f):
49
+ # Optional[T] is a Union[T, None]
50
+ if is_union(type(f)) and type(None) in get_args(type(f)) and f is None:
51
+ return None
52
+ if isinstance(f, Unset):
53
+ return f
54
+
55
+ if not isinstance(f, float):
56
+ raise ValueError("Expected float")
57
+
58
+ return str(f) if as_str else f
59
+
60
+ return serialize
61
+
62
+
63
+ def validate_float(f):
64
+ if f is None:
65
+ return None
66
+
67
+ if isinstance(f, (float, Unset)):
68
+ return f
69
+
70
+ if not isinstance(f, str):
71
+ raise ValueError("Expected string")
72
+
73
+ return float(f)
74
+
75
+
76
+ def serialize_int(as_str: bool):
77
+ def serialize(i):
78
+ # Optional[T] is a Union[T, None]
79
+ if is_union(type(i)) and type(None) in get_args(type(i)) and i is None:
80
+ return None
81
+ if isinstance(i, Unset):
82
+ return i
83
+
84
+ if not isinstance(i, int):
85
+ raise ValueError("Expected int")
86
+
87
+ return str(i) if as_str else i
88
+
89
+ return serialize
90
+
91
+
92
+ def validate_int(b):
93
+ if b is None:
94
+ return None
95
+
96
+ if isinstance(b, (int, Unset)):
97
+ return b
98
+
99
+ if not isinstance(b, str):
100
+ raise ValueError("Expected string")
101
+
102
+ return int(b)
103
+
104
+
105
+ def validate_const(v):
106
+ def validate(c):
107
+ # Optional[T] is a Union[T, None]
108
+ if is_union(type(c)) and type(None) in get_args(type(c)) and c is None:
109
+ return None
110
+
111
+ if v != c:
112
+ raise ValueError(f"Expected {v}")
113
+
114
+ return c
115
+
116
+ return validate
117
+
118
+
119
+ def unmarshal_json(raw, typ: Any) -> Any:
120
+ return unmarshal(from_json(raw), typ)
121
+
122
+
123
+ def unmarshal(val, typ: Any) -> Any:
124
+ unmarshaller = create_model(
125
+ "Unmarshaller",
126
+ body=(typ, ...),
127
+ __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
128
+ )
129
+
130
+ m = unmarshaller(body=val)
131
+
132
+ # pyright: ignore[reportAttributeAccessIssue]
133
+ return m.body # type: ignore
134
+
135
+
136
+ def marshal_json(val, typ):
137
+ if is_nullable(typ) and val is None:
138
+ return "null"
139
+
140
+ marshaller = create_model(
141
+ "Marshaller",
142
+ body=(typ, ...),
143
+ __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
144
+ )
145
+
146
+ m = marshaller(body=val)
147
+
148
+ d = m.model_dump(by_alias=True, mode="json", exclude_none=True)
149
+
150
+ if len(d) == 0:
151
+ return ""
152
+
153
+ return json.dumps(d[next(iter(d))], separators=(",", ":"))
154
+
155
+
156
+ def is_nullable(field):
157
+ origin = get_origin(field)
158
+ if origin is Nullable or origin is OptionalNullable:
159
+ return True
160
+
161
+ if not origin is Union or type(None) not in get_args(field):
162
+ return False
163
+
164
+ for arg in get_args(field):
165
+ if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable:
166
+ return True
167
+
168
+ return False
169
+
170
+
171
+ def is_union(obj: object) -> bool:
172
+ """
173
+ Returns True if the given object is a typing.Union or typing_extensions.Union.
174
+ """
175
+ return any(
176
+ obj is typing_obj for typing_obj in _get_typing_objects_by_name_of("Union")
177
+ )
178
+
179
+
180
+ def stream_to_text(stream: httpx.Response) -> str:
181
+ return "".join(stream.iter_text())
182
+
183
+
184
+ async def stream_to_text_async(stream: httpx.Response) -> str:
185
+ return "".join([chunk async for chunk in stream.aiter_text()])
186
+
187
+
188
+ def stream_to_bytes(stream: httpx.Response) -> bytes:
189
+ return stream.content
190
+
191
+
192
+ async def stream_to_bytes_async(stream: httpx.Response) -> bytes:
193
+ return await stream.aread()
194
+
195
+
196
+ def get_pydantic_model(data: Any, typ: Any) -> Any:
197
+ if not _contains_pydantic_model(data):
198
+ return unmarshal(data, typ)
199
+
200
+ return data
201
+
202
+
203
+ def _contains_pydantic_model(data: Any) -> bool:
204
+ if isinstance(data, BaseModel):
205
+ return True
206
+ if isinstance(data, List):
207
+ return any(_contains_pydantic_model(item) for item in data)
208
+ if isinstance(data, Dict):
209
+ return any(_contains_pydantic_model(value) for value in data.values())
210
+
211
+ return False
212
+
213
+
214
+ @functools.cache
215
+ def _get_typing_objects_by_name_of(name: str) -> Tuple[Any, ...]:
216
+ """
217
+ Get typing objects by name from typing and typing_extensions.
218
+ Reference: https://typing-extensions.readthedocs.io/en/latest/#runtime-use-of-types
219
+ """
220
+ result = tuple(
221
+ getattr(module, name)
222
+ for module in (typing, typing_extensions)
223
+ if hasattr(module, name)
224
+ )
225
+ if not result:
226
+ raise ValueError(
227
+ f"Neither typing nor typing_extensions has an object called {name!r}"
228
+ )
229
+ return result