hammad-python 0.0.13__py3-none-any.whl → 0.0.15__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 (87) hide show
  1. hammad_python-0.0.15.dist-info/METADATA +184 -0
  2. hammad_python-0.0.15.dist-info/RECORD +4 -0
  3. hammad/__init__.py +0 -180
  4. hammad/_core/__init__.py +0 -1
  5. hammad/_core/_utils/__init__.py +0 -4
  6. hammad/_core/_utils/_import_utils.py +0 -182
  7. hammad/ai/__init__.py +0 -59
  8. hammad/ai/_utils.py +0 -142
  9. hammad/ai/completions/__init__.py +0 -44
  10. hammad/ai/completions/client.py +0 -729
  11. hammad/ai/completions/create.py +0 -686
  12. hammad/ai/completions/types.py +0 -711
  13. hammad/ai/completions/utils.py +0 -374
  14. hammad/ai/embeddings/__init__.py +0 -35
  15. hammad/ai/embeddings/client/__init__.py +0 -1
  16. hammad/ai/embeddings/client/base_embeddings_client.py +0 -26
  17. hammad/ai/embeddings/client/fastembed_text_embeddings_client.py +0 -200
  18. hammad/ai/embeddings/client/litellm_embeddings_client.py +0 -288
  19. hammad/ai/embeddings/create.py +0 -159
  20. hammad/ai/embeddings/types.py +0 -69
  21. hammad/base/__init__.py +0 -35
  22. hammad/base/fields.py +0 -546
  23. hammad/base/model.py +0 -1078
  24. hammad/base/utils.py +0 -280
  25. hammad/cache/__init__.py +0 -48
  26. hammad/cache/base_cache.py +0 -181
  27. hammad/cache/cache.py +0 -169
  28. hammad/cache/decorators.py +0 -261
  29. hammad/cache/file_cache.py +0 -80
  30. hammad/cache/ttl_cache.py +0 -74
  31. hammad/cli/__init__.py +0 -33
  32. hammad/cli/animations.py +0 -604
  33. hammad/cli/plugins.py +0 -781
  34. hammad/cli/styles/__init__.py +0 -55
  35. hammad/cli/styles/settings.py +0 -139
  36. hammad/cli/styles/types.py +0 -358
  37. hammad/cli/styles/utils.py +0 -480
  38. hammad/configuration/__init__.py +0 -35
  39. hammad/configuration/configuration.py +0 -564
  40. hammad/data/__init__.py +0 -39
  41. hammad/data/collections/__init__.py +0 -34
  42. hammad/data/collections/base_collection.py +0 -58
  43. hammad/data/collections/collection.py +0 -452
  44. hammad/data/collections/searchable_collection.py +0 -556
  45. hammad/data/collections/vector_collection.py +0 -603
  46. hammad/data/databases/__init__.py +0 -21
  47. hammad/data/databases/database.py +0 -902
  48. hammad/json/__init__.py +0 -21
  49. hammad/json/converters.py +0 -152
  50. hammad/logging/__init__.py +0 -35
  51. hammad/logging/decorators.py +0 -834
  52. hammad/logging/logger.py +0 -954
  53. hammad/multimodal/__init__.py +0 -24
  54. hammad/multimodal/audio.py +0 -96
  55. hammad/multimodal/image.py +0 -80
  56. hammad/multithreading/__init__.py +0 -304
  57. hammad/py.typed +0 -0
  58. hammad/pydantic/__init__.py +0 -43
  59. hammad/pydantic/converters.py +0 -623
  60. hammad/pydantic/models/__init__.py +0 -28
  61. hammad/pydantic/models/arbitrary_model.py +0 -46
  62. hammad/pydantic/models/cacheable_model.py +0 -79
  63. hammad/pydantic/models/fast_model.py +0 -318
  64. hammad/pydantic/models/function_model.py +0 -176
  65. hammad/pydantic/models/subscriptable_model.py +0 -63
  66. hammad/text/__init__.py +0 -82
  67. hammad/text/converters.py +0 -723
  68. hammad/text/markdown.py +0 -131
  69. hammad/text/text.py +0 -1066
  70. hammad/types/__init__.py +0 -11
  71. hammad/types/file.py +0 -358
  72. hammad/typing/__init__.py +0 -407
  73. hammad/web/__init__.py +0 -43
  74. hammad/web/http/__init__.py +0 -1
  75. hammad/web/http/client.py +0 -944
  76. hammad/web/models.py +0 -245
  77. hammad/web/openapi/__init__.py +0 -0
  78. hammad/web/openapi/client.py +0 -740
  79. hammad/web/search/__init__.py +0 -1
  80. hammad/web/search/client.py +0 -988
  81. hammad/web/utils.py +0 -472
  82. hammad/yaml/__init__.py +0 -30
  83. hammad/yaml/converters.py +0 -19
  84. hammad_python-0.0.13.dist-info/METADATA +0 -38
  85. hammad_python-0.0.13.dist-info/RECORD +0 -85
  86. {hammad_python-0.0.13.dist-info → hammad_python-0.0.15.dist-info}/WHEEL +0 -0
  87. {hammad_python-0.0.13.dist-info → hammad_python-0.0.15.dist-info}/licenses/LICENSE +0 -0
@@ -1,564 +0,0 @@
1
- """hammad.data.types.files.configuration"""
2
-
3
- import os
4
- import configparser
5
- from pathlib import Path
6
- from typing import Any, Self
7
- from dotenv import load_dotenv, dotenv_values
8
- import httpx
9
- import msgspec
10
- import yaml
11
-
12
- from ..types.file import File, FileSource
13
- from ..base.fields import field
14
-
15
- __all__ = (
16
- "Configuration",
17
- "read_configuration_from_file",
18
- "read_configuration_from_url",
19
- "read_configuration_from_os_vars",
20
- "read_configuration_from_os_prefix",
21
- "read_configuration_from_dotenv",
22
- )
23
-
24
-
25
- class Configuration(File):
26
- """Model / structure representation for configuration objects
27
- for both module or application level usage. This class is
28
- nothing more than a glorified key-value store with a
29
- few extra features.
30
-
31
- Inherits from File to provide file operations and extends
32
- with configuration-specific functionality."""
33
-
34
- # Configuration-specific fields
35
- config_data: dict[str, Any] = field(default_factory=dict)
36
- """The actual configuration key-value pairs."""
37
-
38
- format_type: str | None = field(default=None)
39
- """The format type of the configuration (json, toml, yaml, ini, env)."""
40
-
41
- def __post_init__(self):
42
- """Initialize configuration data from file data if available."""
43
- super().__post_init__()
44
-
45
- # If we have data but no config_data, try to parse it
46
- if self.data is not None and not self.config_data:
47
- self._parse_data()
48
-
49
- def _parse_data(self) -> None:
50
- """Parse the file data into configuration format."""
51
- if not self.data:
52
- return
53
-
54
- content = self.data if isinstance(self.data, str) else self.data.decode("utf-8")
55
-
56
- # Determine format from extension or type
57
- format_type = self._detect_format()
58
-
59
- try:
60
- if format_type == "json":
61
- self.config_data = msgspec.json.decode(content.encode("utf-8"))
62
- elif format_type == "toml":
63
- self.config_data = msgspec.toml.decode(content.encode("utf-8"))
64
- elif format_type == "yaml":
65
- # Use PyYAML with unsafe_load for YAML tags like !!python/name:
66
- # This is needed for files like mkdocs.yml that use custom constructors
67
- try:
68
- self.config_data = yaml.unsafe_load(content)
69
- except yaml.constructor.ConstructorError:
70
- # Fallback to safe_load if unsafe_load fails
71
- self.config_data = yaml.safe_load(content)
72
- elif format_type == "ini":
73
- parser = configparser.ConfigParser()
74
- parser.read_string(content)
75
- self.config_data = {
76
- section: dict(parser[section]) for section in parser.sections()
77
- }
78
- elif format_type == "env":
79
- # Parse as dotenv format
80
- lines = content.strip().split("\n")
81
- config_data = {}
82
- for line in lines:
83
- line = line.strip()
84
- if line and not line.startswith("#") and "=" in line:
85
- key, value = line.split("=", 1)
86
- config_data[key.strip()] = value.strip().strip("\"'")
87
- self.config_data = config_data
88
-
89
- self.format_type = format_type
90
- except Exception as e:
91
- raise ValueError(
92
- f"Failed to parse configuration data as {format_type}: {e}"
93
- )
94
-
95
- def _detect_format(self) -> str:
96
- """Detect the configuration format from extension or content."""
97
- if self.format_type:
98
- return self.format_type
99
-
100
- # Try to detect from file extension
101
- # Get extension directly from source path to avoid caching issues
102
- if self.source.path:
103
- ext = self.source.path.suffix.lower()
104
- if ext in [".json"]:
105
- return "json"
106
- elif ext in [".toml"]:
107
- return "toml"
108
- elif ext in [".yaml", ".yml"]:
109
- return "yaml"
110
- elif ext in [".ini", ".cfg", ".conf"]:
111
- return "ini"
112
- elif ext in [".env"]:
113
- return "env"
114
- elif self.extension:
115
- ext = self.extension.lower()
116
- if ext in [".json"]:
117
- return "json"
118
- elif ext in [".toml"]:
119
- return "toml"
120
- elif ext in [".yaml", ".yml"]:
121
- return "yaml"
122
- elif ext in [".ini", ".cfg", ".conf"]:
123
- return "ini"
124
- elif ext in [".env"]:
125
- return "env"
126
-
127
- # Try to detect from MIME type
128
- if self.type:
129
- if "json" in self.type:
130
- return "json"
131
- elif "yaml" in self.type:
132
- return "yaml"
133
-
134
- # Default fallback - try to parse as JSON first
135
- return "json"
136
-
137
- def _serialize_data(self, format_type: str | None = None) -> str:
138
- """Serialize configuration data to string format."""
139
- format_type = format_type or self.format_type or "json"
140
-
141
- if format_type == "json":
142
- return msgspec.json.encode(self.config_data).decode("utf-8")
143
- elif format_type == "toml":
144
- return msgspec.toml.encode(self.config_data).decode("utf-8")
145
- elif format_type == "yaml":
146
- return yaml.dump(
147
- self.config_data, default_flow_style=False, allow_unicode=True
148
- )
149
- elif format_type == "ini":
150
- parser = configparser.ConfigParser()
151
- for section_name, section_data in self.config_data.items():
152
- parser[section_name] = section_data
153
- import io
154
-
155
- output = io.StringIO()
156
- parser.write(output)
157
- return output.getvalue()
158
- elif format_type == "env":
159
- lines = []
160
- for key, value in self.config_data.items():
161
- # Simple escaping for shell variables
162
- if isinstance(value, str) and (
163
- " " in value or '"' in value or "'" in value
164
- ):
165
- value = f'"{value}"'
166
- lines.append(f"{key}={value}")
167
- return "\n".join(lines)
168
- else:
169
- raise ValueError(f"Unsupported format: {format_type}")
170
-
171
- @classmethod
172
- def from_dotenv(cls, path: str | Path | None = None) -> Self:
173
- """Loads a .env file and creates a configuration object
174
- from it.
175
-
176
- NOTE: This does not set any environment variables.
177
-
178
- Args:
179
- path: The path to the .env file to load. If not provided,
180
- the .env file in the current working directory will be used.
181
- """
182
- if path is None:
183
- path = Path.cwd() / ".env"
184
- else:
185
- path = Path(path)
186
-
187
- if not path.exists():
188
- raise FileNotFoundError(f"Environment file not found: {path}")
189
-
190
- # Use dotenv_values to parse without setting environment variables
191
- config_data = dotenv_values(path)
192
-
193
- return cls(
194
- config_data=dict(config_data),
195
- format_type="env",
196
- source=FileSource(
197
- is_file=True,
198
- path=path,
199
- size=path.stat().st_size if path.exists() else None,
200
- ),
201
- type="text/plain",
202
- )
203
-
204
- @classmethod
205
- def from_os_prefix(cls, prefix: str) -> Self:
206
- """Creates a new configuration object using all variables
207
- that begin with the given prefix.
208
-
209
- Args:
210
- prefix: The prefix to use to filter the variables.
211
- """
212
- config_data = {}
213
- for key, value in os.environ.items():
214
- if key.startswith(prefix):
215
- # Remove prefix and convert to lowercase
216
- config_key = key[len(prefix) :].lstrip("_").lower()
217
- config_data[config_key] = value
218
-
219
- return cls(
220
- config_data=config_data,
221
- format_type="env",
222
- source=FileSource(),
223
- type="text/plain",
224
- )
225
-
226
- @classmethod
227
- def from_os_vars(cls, vars: list[str]) -> Self:
228
- """Pulls a certain set of environment variables and
229
- creates a configuration object from them.
230
-
231
- Args:
232
- vars: A list of environment variable names to pull.
233
- """
234
- config_data = {}
235
- for var in vars:
236
- if var in os.environ:
237
- config_data[var] = os.environ[var]
238
-
239
- return cls(
240
- config_data=config_data,
241
- format_type="env",
242
- source=FileSource(),
243
- type="text/plain",
244
- )
245
-
246
- @classmethod
247
- def from_file(
248
- cls,
249
- path: str | Path,
250
- ) -> Self:
251
- """Parses a file to return a configuration object. This
252
- utilizes the following file types:
253
-
254
- - json
255
- - toml
256
- - yaml
257
- - ini
258
- - env
259
- """
260
- # Use the parent File class to load the file
261
- file_obj = File.from_path(path, lazy=False)
262
-
263
- # Create a Configuration object from the File object
264
- config = cls(
265
- data=file_obj.data,
266
- type=file_obj.type,
267
- source=file_obj.source,
268
- )
269
-
270
- # Parse the data
271
- config._parse_data()
272
-
273
- return config
274
-
275
- @classmethod
276
- def from_url(
277
- cls,
278
- url: str,
279
- *,
280
- timeout: float = 30.0,
281
- headers: dict[str, str] | None = None,
282
- ) -> Self:
283
- """Load configuration from a URL supporting various formats.
284
-
285
- Args:
286
- url: The URL to load configuration from
287
- timeout: Request timeout in seconds
288
- headers: Optional HTTP headers to include in the request
289
-
290
- Returns:
291
- A new Configuration instance
292
- """
293
- with httpx.Client(timeout=timeout) as client:
294
- response = client.get(url, headers=headers or {})
295
- response.raise_for_status()
296
-
297
- # Get content as text
298
- content = response.text
299
-
300
- # Determine format from URL extension or content-type
301
- format_type = None
302
- if url.endswith(".json"):
303
- format_type = "json"
304
- elif url.endswith((".yaml", ".yml")):
305
- format_type = "yaml"
306
- elif url.endswith(".toml"):
307
- format_type = "toml"
308
- elif url.endswith((".ini", ".cfg", ".conf")):
309
- format_type = "ini"
310
- elif url.endswith(".env"):
311
- format_type = "env"
312
- else:
313
- # Try to detect from content-type header
314
- content_type = response.headers.get("content-type", "").lower()
315
- if "json" in content_type:
316
- format_type = "json"
317
- elif "yaml" in content_type:
318
- format_type = "yaml"
319
-
320
- config = cls(
321
- data=content,
322
- type=response.headers.get("content-type"),
323
- format_type=format_type,
324
- source=FileSource(
325
- is_url=True,
326
- url=url,
327
- size=len(content.encode("utf-8")),
328
- encoding=response.encoding,
329
- ),
330
- )
331
-
332
- config._parse_data()
333
- return config
334
-
335
- def to_file(
336
- self,
337
- path: str | Path,
338
- *,
339
- overwrite: bool = False,
340
- format_type: str | None = None,
341
- ) -> None:
342
- """Saves the configuration object to a file. This
343
- utilizes the following file types:
344
-
345
- - json
346
- - toml
347
- - yaml
348
- - ini
349
- - env
350
-
351
- Args:
352
- path: The path to the file to save the configuration to.
353
- overwrite: Whether to overwrite the file if it already exists.
354
- format_type: Override the format type for saving.
355
- """
356
- save_path = Path(path)
357
-
358
- if save_path.exists() and not overwrite:
359
- raise FileExistsError(f"File already exists: {save_path}")
360
-
361
- # Determine format from path extension if not specified
362
- if format_type is None:
363
- ext = save_path.suffix.lower()
364
- if ext in [".json"]:
365
- format_type = "json"
366
- elif ext in [".toml"]:
367
- format_type = "toml"
368
- elif ext in [".yaml", ".yml"]:
369
- format_type = "yaml"
370
- elif ext in [".ini", ".cfg", ".conf"]:
371
- format_type = "ini"
372
- elif ext in [".env"]:
373
- format_type = "env"
374
- else:
375
- format_type = self.format_type or "json"
376
-
377
- # Serialize and save
378
- content = self._serialize_data(format_type)
379
- save_path.parent.mkdir(parents=True, exist_ok=True)
380
- save_path.write_text(content, encoding="utf-8")
381
-
382
- def update_file(
383
- self,
384
- path: str | Path,
385
- exclude: list[str] | None = None,
386
- exclude_none: bool = True,
387
- ) -> None:
388
- """Updates a valid configuration file with only the
389
- differing values.
390
-
391
- Args:
392
- path: The path to the file to update.
393
- exclude: A list of keys to exclude from the update.
394
- exclude_none: Whether to exclude keys with None values.
395
- """
396
- path = Path(path)
397
-
398
- if not path.exists():
399
- raise FileNotFoundError(f"Configuration file not found: {path}")
400
-
401
- # Load existing configuration
402
- existing_config = Configuration.from_file(path)
403
-
404
- # Prepare data to update
405
- update_data = self.config_data.copy()
406
-
407
- if exclude:
408
- for key in exclude:
409
- update_data.pop(key, None)
410
-
411
- if exclude_none:
412
- update_data = {k: v for k, v in update_data.items() if v is not None}
413
-
414
- # Merge with existing data
415
- existing_config.config_data.update(update_data)
416
-
417
- # Save back to file
418
- existing_config.to_file(path, overwrite=True)
419
-
420
- def to_os(
421
- self,
422
- prefix: str | None = None,
423
- exclude: list[str] | None = None,
424
- ) -> None:
425
- """Pushes the configuration object's values as active
426
- environment variables. This will overwrite any existing
427
- values for the session.
428
-
429
- Args:
430
- prefix: The prefix to use to filter the variables.
431
- exclude: A list of keys to exclude from the update.
432
- """
433
- exclude = exclude or []
434
-
435
- for key, value in self.config_data.items():
436
- if key in exclude:
437
- continue
438
-
439
- # Convert value to string
440
- env_value = str(value) if value is not None else ""
441
-
442
- # Apply prefix if specified
443
- env_key = f"{prefix}_{key}".upper() if prefix else key.upper()
444
-
445
- # Set environment variable
446
- os.environ[env_key] = env_value
447
-
448
- def get(self, key: str, default: Any = None) -> Any:
449
- """Get a configuration value by key.
450
-
451
- Args:
452
- key: The configuration key
453
- default: Default value if key is not found
454
-
455
- Returns:
456
- The configuration value or default
457
- """
458
- return self.config_data.get(key, default)
459
-
460
- def set(self, key: str, value: Any) -> None:
461
- """Set a configuration value.
462
-
463
- Args:
464
- key: The configuration key
465
- value: The value to set
466
- """
467
- self.config_data[key] = value
468
-
469
- def __getitem__(self, key: str) -> Any:
470
- """Get configuration value using dict-like access."""
471
- return self.config_data[key]
472
-
473
- def __setitem__(self, key: str, value: Any) -> None:
474
- """Set configuration value using dict-like access."""
475
- self.config_data[key] = value
476
-
477
- def __contains__(self, key: str) -> bool:
478
- """Check if configuration contains a key."""
479
- return key in self.config_data
480
-
481
- def keys(self):
482
- """Return configuration keys."""
483
- return self.config_data.keys()
484
-
485
- def values(self):
486
- """Return configuration values."""
487
- return self.config_data.values()
488
-
489
- def items(self):
490
- """Return configuration key-value pairs."""
491
- return self.config_data.items()
492
-
493
-
494
- # HELPERS
495
-
496
-
497
- def read_configuration_from_file(path: str | Path) -> Configuration:
498
- """Parse a filepath into a `Configuration` object.
499
-
500
- Valid file types:
501
- - json
502
- - toml
503
- - yaml
504
- - ini
505
- - env
506
-
507
- Args:
508
- path: The path to the file to parse.
509
-
510
- Returns:
511
- A `Configuration` object.
512
- """
513
- file_obj = File.from_path(path, lazy=False)
514
- return Configuration.from_file(file_obj)
515
-
516
-
517
- def read_configuration_from_url(url: str) -> Configuration:
518
- """Parse a URL into a `Configuration` object.
519
-
520
- Args:
521
- url: The URL to parse.
522
-
523
- Returns:
524
- A `Configuration` object.
525
- """
526
- return Configuration.from_url(url)
527
-
528
-
529
- def read_configuration_from_os_vars(vars: list[str]) -> Configuration:
530
- """Parse a list of environment variables into a `Configuration` object.
531
-
532
- Args:
533
- vars: The list of environment variables to parse.
534
-
535
- Returns:
536
- A `Configuration` object.
537
- """
538
- return Configuration.from_os_vars(vars)
539
-
540
-
541
- def read_configuration_from_os_prefix(prefix: str) -> Configuration:
542
- """Parse a list of environment variables into a `Configuration` object.
543
-
544
- Args:
545
- prefix: The prefix to use to filter the variables.
546
-
547
- Returns:
548
- A `Configuration` object.
549
- """
550
- return Configuration.from_os_prefix(prefix)
551
-
552
-
553
- def read_configuration_from_dotenv(path: str | Path = ".env") -> Configuration:
554
- """Parse a .env file into a `Configuration` object.
555
-
556
- NOTE: Defaults to `.env` in the current working directory.
557
-
558
- Args:
559
- path: The path to the .env file to parse.
560
-
561
- Returns:
562
- A `Configuration` object.
563
- """
564
- return Configuration.from_dotenv(path)
hammad/data/__init__.py DELETED
@@ -1,39 +0,0 @@
1
- """hammad.data"""
2
-
3
- from typing import TYPE_CHECKING
4
- from .._core._utils._import_utils import _auto_create_getattr_loader
5
-
6
- if TYPE_CHECKING:
7
- from .collections import (
8
- Collection,
9
- BaseCollection,
10
- VectorCollection,
11
- VectorCollectionSettings,
12
- SearchableCollection,
13
- SearchableCollectionSettings,
14
- create_collection,
15
- )
16
- from .databases import Database, create_database
17
-
18
-
19
- __all__ = (
20
- # hammad.data.collections
21
- "Collection",
22
- "BaseCollection",
23
- "VectorCollection",
24
- "VectorCollectionSettings",
25
- "SearchableCollection",
26
- "SearchableCollectionSettings",
27
- "create_collection",
28
- # hammad.data.databases
29
- "Database",
30
- "create_database",
31
- )
32
-
33
-
34
- __getattr__ = _auto_create_getattr_loader(__all__)
35
-
36
-
37
- def __dir__() -> list[str]:
38
- """Get the attributes of the data module."""
39
- return list(__all__)
@@ -1,34 +0,0 @@
1
- """hammad.data.collections"""
2
-
3
- from typing import TYPE_CHECKING
4
- from ..._core._utils._import_utils import _auto_create_getattr_loader
5
-
6
- if TYPE_CHECKING:
7
- from .base_collection import BaseCollection
8
- from .searchable_collection import SearchableCollection
9
- from .vector_collection import VectorCollection
10
- from .collection import (
11
- create_collection,
12
- VectorCollectionSettings,
13
- SearchableCollectionSettings,
14
- Collection,
15
- )
16
-
17
-
18
- __all__ = (
19
- "BaseCollection",
20
- "SearchableCollection",
21
- "VectorCollection",
22
- "create_collection",
23
- "VectorCollectionSettings",
24
- "SearchableCollectionSettings",
25
- "Collection",
26
- )
27
-
28
-
29
- __getattr__ = _auto_create_getattr_loader(__all__)
30
-
31
-
32
- def __dir__() -> list[str]:
33
- """Get the attributes of the data.collections module."""
34
- return list(__all__)
@@ -1,58 +0,0 @@
1
- """hammad.data.collections.base_collection"""
2
-
3
- from typing import Any, Dict, Optional, List, TypeVar, Union, Type, Generic
4
- from abc import ABC, abstractmethod
5
-
6
- __all__ = (
7
- "BaseCollection",
8
- "Object",
9
- "Filters",
10
- "Schema",
11
- )
12
-
13
-
14
- Object = TypeVar("Object")
15
- """Represents an object that can be stored within a collection."""
16
-
17
-
18
- Filters = Dict[str, object]
19
- """Represents a dictionary of filters that can be applied to objects within
20
- a collection."""
21
-
22
-
23
- Schema = Union[Type[Any], Dict[str, Any], None]
24
- """Represents a strict schema that a collection can optionally enforce."""
25
-
26
-
27
- class BaseCollection(ABC, Generic[Object]):
28
- """Base class defining the interface for collections. This
29
- class does not provide any functionality.
30
- """
31
-
32
- @abstractmethod
33
- def get(self, id: str, *, filters: Optional[Filters] = None) -> Optional[Any]:
34
- """Get an item by ID."""
35
- pass
36
-
37
- @abstractmethod
38
- def add(
39
- self,
40
- entry: Any,
41
- *,
42
- id: Optional[str] = None,
43
- filters: Optional[Filters] = None,
44
- ttl: Optional[int] = None,
45
- ) -> None:
46
- """Add an item to the collection."""
47
- pass
48
-
49
- @abstractmethod
50
- def query(
51
- self,
52
- *,
53
- filters: Optional[Filters] = None,
54
- search: Optional[str] = None,
55
- limit: Optional[int] = None,
56
- ) -> List[Any]:
57
- """Query items from the collection."""
58
- pass