0
# Basic Field Types
1
2
Essential field types for common data validation and conversion in Schematics. These types handle fundamental data types with comprehensive validation options and automatic type conversion.
3
4
## Capabilities
5
6
### String Fields
7
8
Handle text data with length validation, pattern matching, and encoding support.
9
10
```python { .api }
11
class StringType(BaseType):
12
"""
13
Unicode string field with validation and formatting.
14
15
Supports regex patterns, length constraints, and custom validation.
16
Automatically converts input to Unicode strings.
17
"""
18
19
def __init__(self, regex=None, max_length=None, min_length=None, **kwargs):
20
"""
21
Initialize string field.
22
23
Args:
24
regex (str, optional): Regular expression pattern for validation
25
max_length (int, optional): Maximum string length
26
min_length (int, optional): Minimum string length
27
**kwargs: Base field options (required, default, etc.)
28
"""
29
30
class MultilingualStringType(BaseType):
31
"""
32
Multi-language string field with localization support.
33
34
Stores strings in multiple languages with locale-based retrieval.
35
"""
36
```
37
38
### Numeric Fields
39
40
Handle various numeric types with range validation and precision control.
41
42
```python { .api }
43
class IntType(BaseType):
44
"""
45
Integer field with range validation.
46
47
Converts strings and floats to integers with optional min/max constraints.
48
"""
49
50
def __init__(self, min_value=None, max_value=None, **kwargs):
51
"""
52
Initialize integer field.
53
54
Args:
55
min_value (int, optional): Minimum allowed value
56
max_value (int, optional): Maximum allowed value
57
**kwargs: Base field options
58
"""
59
60
class LongType(IntType):
61
"""
62
Alias for IntType providing Python 2/3 compatibility.
63
"""
64
65
class FloatType(BaseType):
66
"""
67
Float field with range validation and precision handling.
68
"""
69
70
def __init__(self, min_value=None, max_value=None, **kwargs):
71
"""
72
Initialize float field.
73
74
Args:
75
min_value (float, optional): Minimum allowed value
76
max_value (float, optional): Maximum allowed value
77
**kwargs: Base field options
78
"""
79
80
class DecimalType(BaseType):
81
"""
82
Fixed-point decimal field using Python's Decimal type.
83
84
Provides exact decimal arithmetic for financial calculations.
85
"""
86
87
def __init__(self, min_value=None, max_value=None, **kwargs):
88
"""
89
Initialize decimal field.
90
91
Args:
92
min_value (Decimal, optional): Minimum allowed value
93
max_value (Decimal, optional): Maximum allowed value
94
**kwargs: Base field options
95
"""
96
97
class NumberType(BaseType):
98
"""
99
Generic number field accepting int, float, or Decimal.
100
101
Base class for numeric types with common validation logic.
102
"""
103
```
104
105
### Boolean Fields
106
107
Handle boolean data with flexible input conversion.
108
109
```python { .api }
110
class BooleanType(BaseType):
111
"""
112
Boolean field with string coercion support.
113
114
Converts various string representations ('true', 'false', '1', '0')
115
and numeric values to boolean.
116
"""
117
118
def __init__(self, **kwargs):
119
"""
120
Initialize boolean field.
121
122
Args:
123
**kwargs: Base field options
124
"""
125
```
126
127
### UUID Fields
128
129
Handle UUID data with format validation and conversion.
130
131
```python { .api }
132
class UUIDType(BaseType):
133
"""
134
UUID field supporting string and UUID object input.
135
136
Validates UUID format and converts between string and UUID objects.
137
"""
138
139
def __init__(self, **kwargs):
140
"""
141
Initialize UUID field.
142
143
Args:
144
**kwargs: Base field options
145
"""
146
```
147
148
### Date and Time Fields
149
150
Handle temporal data with format parsing and timezone support.
151
152
```python { .api }
153
class DateType(BaseType):
154
"""
155
Date field with ISO8601 string parsing.
156
157
Converts date strings to Python date objects with format validation.
158
"""
159
160
def __init__(self, formats=None, **kwargs):
161
"""
162
Initialize date field.
163
164
Args:
165
formats (list, optional): Custom date format strings
166
**kwargs: Base field options
167
"""
168
169
class DateTimeType(BaseType):
170
"""
171
DateTime field with timezone and format support.
172
173
Handles various datetime formats and timezone conversions.
174
"""
175
176
def __init__(self, formats=None, convert_tz=True, **kwargs):
177
"""
178
Initialize datetime field.
179
180
Args:
181
formats (list, optional): Custom datetime format strings
182
convert_tz (bool): Whether to handle timezone conversion
183
**kwargs: Base field options
184
"""
185
186
class UTCDateTimeType(DateTimeType):
187
"""
188
UTC-normalized datetime field.
189
190
Automatically converts all datetime values to UTC timezone.
191
"""
192
193
class TimestampType(BaseType):
194
"""
195
Unix timestamp field converting float/int to datetime.
196
197
Handles Unix timestamps (seconds since epoch) with datetime conversion.
198
"""
199
200
class TimedeltaType(BaseType):
201
"""
202
Time duration field using Python's timedelta.
203
204
Supports various duration input formats and timedelta objects.
205
"""
206
```
207
208
### Hash Fields
209
210
Handle cryptographic hashes with format validation.
211
212
```python { .api }
213
class HashType(BaseType):
214
"""
215
Base class for hash fields with length and character validation.
216
217
Validates hexadecimal hash strings of specified lengths.
218
"""
219
220
class MD5Type(HashType):
221
"""
222
MD5 hash field (32 hexadecimal characters).
223
224
Validates MD5 hash format and case-insensitive input.
225
"""
226
227
class SHA1Type(HashType):
228
"""
229
SHA1 hash field (40 hexadecimal characters).
230
231
Validates SHA1 hash format and case-insensitive input.
232
"""
233
```
234
235
### Geographic Fields
236
237
Handle geographic coordinate data.
238
239
```python { .api }
240
class GeoPointType(BaseType):
241
"""
242
Geographic coordinate field storing [latitude, longitude] pairs.
243
244
Validates coordinate ranges and supports various input formats.
245
"""
246
247
def __init__(self, **kwargs):
248
"""
249
Initialize geographic point field.
250
251
Args:
252
**kwargs: Base field options
253
"""
254
```
255
256
### Base Field Type
257
258
All field types inherit from BaseType which provides common functionality.
259
260
```python { .api }
261
class BaseType:
262
"""
263
Base class for all field types providing common validation and conversion.
264
265
Defines the field interface and shared functionality for validation,
266
conversion, serialization, and mock data generation.
267
"""
268
269
def __init__(self, required=False, default=Undefined, serialized_name=None,
270
choices=None, validators=None, deserialize_from=None,
271
export_level=None, serialize_when_none=None,
272
messages=None, metadata=None):
273
"""
274
Initialize base field type.
275
276
Args:
277
required (bool): Whether field is required
278
default: Default value if not provided (Undefined for no default)
279
serialized_name (str, optional): Name for serialization
280
choices (list, optional): Allowed values
281
validators (list, optional): Additional validator functions
282
deserialize_from (str/list, optional): Source field names for deserialization
283
export_level (int, optional): Export level for field inclusion
284
serialize_when_none (bool, optional): Whether to serialize None values
285
messages (dict, optional): Custom error messages
286
metadata (dict, optional): Additional field metadata
287
"""
288
289
def validate(self, value, context=None):
290
"""
291
Validate field value according to field rules.
292
293
Args:
294
value: Value to validate
295
context: Validation context
296
297
Raises:
298
ValidationError: If validation fails
299
"""
300
301
def convert(self, value, context=None):
302
"""
303
Convert input value to field's native type.
304
305
Args:
306
value: Value to convert
307
context: Conversion context
308
309
Returns:
310
Converted value
311
312
Raises:
313
ConversionError: If conversion fails
314
"""
315
```
316
317
## Usage Examples
318
319
### String Validation
320
321
```python
322
from schematics.models import Model
323
from schematics.types import StringType
324
325
class User(Model):
326
username = StringType(required=True, min_length=3, max_length=20,
327
regex=r'^[a-zA-Z0-9_]+$')
328
email = StringType(required=True)
329
bio = StringType(max_length=500)
330
331
# Valid data
332
user = User({
333
'username': 'john_doe',
334
'email': 'john@example.com',
335
'bio': 'Software developer'
336
})
337
user.validate() # Success
338
```
339
340
### Numeric Validation
341
342
```python
343
from schematics.types import IntType, FloatType, DecimalType
344
from decimal import Decimal
345
346
class Product(Model):
347
quantity = IntType(min_value=0, required=True)
348
weight = FloatType(min_value=0.0, max_value=1000.0)
349
price = DecimalType(min_value=Decimal('0.00'), required=True)
350
351
product = Product({
352
'quantity': 10,
353
'weight': 2.5,
354
'price': '19.99' # String converted to Decimal
355
})
356
product.validate()
357
```
358
359
### Date/Time Handling
360
361
```python
362
from schematics.types import DateType, DateTimeType, TimestampType
363
from datetime import datetime
364
365
class Event(Model):
366
event_date = DateType(required=True)
367
created_at = DateTimeType(default=datetime.utcnow)
368
timestamp = TimestampType()
369
370
# Various input formats supported
371
event = Event({
372
'event_date': '2024-12-25', # ISO date string
373
'timestamp': 1640995200 # Unix timestamp
374
})
375
event.validate()
376
```