0
# Schema Management
1
2
Cerberus provides a comprehensive schema management system including schema validation, registries for reusable schemas and rule sets, and extensible schema definitions. This enables structured schema reuse and validation across applications.
3
4
## Capabilities
5
6
### DefinitionSchema Class
7
8
A specialized dictionary-like class for validated schema storage and manipulation.
9
10
```python { .api }
11
class DefinitionSchema:
12
def __init__(self, validator, schema):
13
"""
14
Initialize a definition schema.
15
16
Parameters:
17
- validator: Validator instance that uses this schema
18
- schema: Schema definition as dict or string reference to registered schema
19
"""
20
21
def validate(self, schema=None):
22
"""
23
Validate a schema against supported validation rules.
24
25
Parameters:
26
- schema: Schema to validate (dict, optional - defaults to current schema)
27
28
Raises:
29
SchemaError: If schema is invalid
30
"""
31
32
def copy(self):
33
"""
34
Return a copy of the schema.
35
36
Returns:
37
DefinitionSchema: Copy of current schema
38
"""
39
40
def update(self, schema):
41
"""
42
Update schema with new definitions.
43
44
Parameters:
45
- schema: Schema updates to apply (dict)
46
"""
47
48
@classmethod
49
def expand(cls, schema):
50
"""
51
Expand schema shortcuts and references.
52
53
Parameters:
54
- schema: Schema to expand (dict)
55
56
Returns:
57
dict: Expanded schema
58
"""
59
60
# Dictionary-like interface
61
def __getitem__(self, key): ...
62
def __setitem__(self, key, value): ...
63
def __delitem__(self, key): ...
64
def __iter__(self): ...
65
def __len__(self): ...
66
def get(self, key, default=None): ...
67
def items(self): ...
68
def keys(self): ...
69
def values(self): ...
70
```
71
72
### Registry System
73
74
Base registry class for storing and retrieving named definitions.
75
76
```python { .api }
77
class Registry:
78
def add(self, name, definition):
79
"""
80
Register a definition by name.
81
82
Parameters:
83
- name: Name to register under (str)
84
- definition: Definition to store
85
"""
86
87
def get(self, name, default=None):
88
"""
89
Retrieve a registered definition.
90
91
Parameters:
92
- name: Name of definition to retrieve (str)
93
- default: Default value if not found
94
95
Returns:
96
Definition or default value
97
"""
98
99
def extend(self, definitions):
100
"""
101
Add multiple definitions from a dictionary.
102
103
Parameters:
104
- definitions: Dictionary of name -> definition mappings (dict)
105
"""
106
107
def remove(self, *names):
108
"""
109
Unregister definitions by name.
110
111
Parameters:
112
- names: Names of definitions to remove (str)
113
"""
114
115
def clear(self):
116
"""Remove all registered definitions."""
117
118
def all(self):
119
"""
120
Return dictionary of all registered definitions.
121
122
Returns:
123
dict: All registered definitions
124
"""
125
```
126
127
### Schema Registry
128
129
Specialized registry for schema definitions.
130
131
```python { .api }
132
class SchemaRegistry(Registry):
133
"""Registry for storing and retrieving schema definitions by name."""
134
```
135
136
### Rules Set Registry
137
138
Specialized registry for rules set definitions.
139
140
```python { .api }
141
class RulesSetRegistry(Registry):
142
"""Registry for storing and retrieving rule set definitions by name."""
143
```
144
145
### Global Registry Instances
146
147
Pre-configured global registry instances for application-wide schema and rules storage.
148
149
```python { .api }
150
schema_registry: SchemaRegistry
151
"""Global registry instance for storing schemas by name"""
152
153
rules_set_registry: RulesSetRegistry
154
"""Global registry instance for storing rule sets by name"""
155
```
156
157
## Exception Classes
158
159
```python { .api }
160
class SchemaError(Exception):
161
"""Raised when validation schema is missing, malformed, or contains errors"""
162
```
163
164
## Usage Examples
165
166
### Basic Schema Definition
167
168
```python
169
from cerberus import Validator, DefinitionSchema
170
171
# Create schema directly
172
schema_dict = {
173
'name': {'type': 'string', 'minlength': 2},
174
'age': {'type': 'integer', 'min': 0}
175
}
176
177
validator = Validator(schema_dict)
178
179
# Access the schema object
180
definition_schema = validator.schema
181
print(type(definition_schema)) # <class 'cerberus.schema.DefinitionSchema'>
182
```
183
184
### Schema Validation
185
186
```python
187
from cerberus import Validator, SchemaError
188
189
# Valid schema
190
valid_schema = {
191
'name': {'type': 'string'},
192
'age': {'type': 'integer'}
193
}
194
195
# Invalid schema - will raise SchemaError
196
try:
197
invalid_schema = {
198
'name': {'type': 'invalid_type'}, # Invalid type
199
'age': {'type': 'integer', 'min': 'not_a_number'} # Invalid constraint
200
}
201
v = Validator(invalid_schema)
202
except SchemaError as e:
203
print(f"Schema error: {e}")
204
```
205
206
### Schema Registry Usage
207
208
```python
209
from cerberus import Validator, schema_registry
210
211
# Register schemas globally
212
schema_registry.add('user', {
213
'name': {'type': 'string', 'minlength': 2},
214
'email': {'type': 'string', 'regex': r'^[^@]+@[^@]+\.[^@]+$'},
215
'age': {'type': 'integer', 'min': 18}
216
})
217
218
schema_registry.add('product', {
219
'name': {'type': 'string', 'required': True},
220
'price': {'type': 'float', 'min': 0},
221
'category': {'type': 'string', 'allowed': ['electronics', 'books', 'clothing']}
222
})
223
224
# Use registered schemas
225
user_validator = Validator('user') # References registered schema
226
product_validator = Validator('product')
227
228
# Validate documents
229
user_doc = {'name': 'John', 'email': 'john@example.com', 'age': 25}
230
print(user_validator.validate(user_doc)) # True
231
232
# Retrieve registered schemas
233
user_schema = schema_registry.get('user')
234
all_schemas = schema_registry.all()
235
```
236
237
### Rules Set Registry Usage
238
239
```python
240
from cerberus import Validator, rules_set_registry
241
242
# Register common rule sets
243
rules_set_registry.add('string_rules', {
244
'type': 'string',
245
'minlength': 1,
246
'maxlength': 100
247
})
248
249
rules_set_registry.add('email_rules', {
250
'type': 'string',
251
'regex': r'^[^@]+@[^@]+\.[^@]+$'
252
})
253
254
# Use rule sets in schemas
255
schema = {
256
'name': 'string_rules', # References registered rule set
257
'email': 'email_rules',
258
'description': {'type': 'string', 'maxlength': 500}
259
}
260
261
v = Validator(schema)
262
```
263
264
### Multiple Registries
265
266
```python
267
from cerberus import schema_registry, rules_set_registry
268
269
# Add multiple definitions at once
270
schemas = {
271
'person': {'name': {'type': 'string'}, 'age': {'type': 'integer'}},
272
'address': {'street': {'type': 'string'}, 'city': {'type': 'string'}}
273
}
274
schema_registry.extend(schemas)
275
276
# Remove definitions
277
schema_registry.remove('person', 'address')
278
279
# Clear all definitions
280
schema_registry.clear()
281
```
282
283
### Schema Updates and Copying
284
285
```python
286
from cerberus import Validator
287
288
schema = {
289
'name': {'type': 'string'},
290
'age': {'type': 'integer'}
291
}
292
293
v = Validator(schema)
294
295
# Update schema
296
v.schema.update({
297
'email': {'type': 'string', 'regex': r'^[^@]+@[^@]+\.[^@]+$'}
298
})
299
300
# Copy schema
301
schema_copy = v.schema.copy()
302
303
# Modify copy without affecting original
304
schema_copy['phone'] = {'type': 'string'}
305
```
306
307
### Schema References
308
309
```python
310
from cerberus import Validator, schema_registry
311
312
# Register base schemas
313
schema_registry.add('base_person', {
314
'name': {'type': 'string', 'required': True},
315
'age': {'type': 'integer', 'min': 0}
316
})
317
318
# Create validator using registered schema
319
v = Validator('base_person')
320
321
# Extend with additional fields
322
v.schema.update({
323
'email': {'type': 'string', 'required': True},
324
'phone': {'type': 'string'}
325
})
326
```
327
328
### Schema Expansion
329
330
```python
331
from cerberus import DefinitionSchema
332
333
# Schema with shortcuts
334
schema_with_shortcuts = {
335
'name': 'string', # Shortcut for {'type': 'string'}
336
'tags': ['string'], # Shortcut for list of strings
337
'metadata': {'type': 'dict'}
338
}
339
340
# Expand shortcuts
341
expanded = DefinitionSchema.expand(schema_with_shortcuts)
342
print(expanded)
343
# Output: {
344
# 'name': {'type': 'string'},
345
# 'tags': {'type': 'list', 'schema': {'type': 'string'}},
346
# 'metadata': {'type': 'dict'}
347
# }
348
```