Skip to content

Commit c17e763

Browse files
committed
reformatted
1 parent 94e86f2 commit c17e763

File tree

7 files changed

+360
-225
lines changed

7 files changed

+360
-225
lines changed

examples/json_schema_export.py

Lines changed: 94 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,42 @@
1313
"""
1414

1515
import json
16+
1617
from voluptuous import (
17-
Schema, Required, Optional, All, Any, Range, Length, In, Match,
18-
Email, Url, Date, Datetime, Coerce, Clamp, ExactSequence, to_json_schema
18+
All,
19+
Any,
20+
Clamp,
21+
Coerce,
22+
Date,
23+
Datetime,
24+
Email,
25+
ExactSequence,
26+
In,
27+
Length,
28+
Match,
29+
Optional,
30+
Range,
31+
Required,
32+
Schema,
33+
Url,
34+
to_json_schema,
1935
)
2036

2137

2238
def example_basic_types():
2339
"""Demonstrate basic type conversion."""
2440
print("=== Basic Types ===")
25-
41+
2642
# Simple types
2743
schemas = {
2844
"String": Schema(str),
2945
"Integer": Schema(int),
3046
"Float": Schema(float),
3147
"Boolean": Schema(bool),
3248
"Literal": Schema("hello"),
33-
"None": Schema(None)
49+
"None": Schema(None),
3450
}
35-
51+
3652
for name, schema in schemas.items():
3753
json_schema = schema.to_json_schema()
3854
print(f"{name}: {json.dumps(json_schema, indent=2)}")
@@ -42,20 +58,22 @@ def example_basic_types():
4258
def example_object_schemas():
4359
"""Demonstrate object schema conversion."""
4460
print("=== Object Schemas ===")
45-
61+
4662
# User profile schema
47-
user_schema = Schema({
48-
Required('username'): All(str, Length(min=3, max=20)),
49-
Required('email'): Email(),
50-
Optional('age'): Range(min=13, max=120),
51-
Optional('bio', default=""): All(str, Length(max=500)),
52-
Optional('preferences'): {
53-
'theme': In(['light', 'dark', 'auto']),
54-
'notifications': bool,
55-
'language': str
63+
user_schema = Schema(
64+
{
65+
Required('username'): All(str, Length(min=3, max=20)),
66+
Required('email'): Email(),
67+
Optional('age'): Range(min=13, max=120),
68+
Optional('bio', default=""): All(str, Length(max=500)),
69+
Optional('preferences'): {
70+
'theme': In(['light', 'dark', 'auto']),
71+
'notifications': bool,
72+
'language': str,
73+
},
5674
}
57-
})
58-
75+
)
76+
5977
json_schema = user_schema.to_json_schema()
6078
print("User Profile Schema:")
6179
print(json.dumps(json_schema, indent=2))
@@ -65,19 +83,19 @@ def example_object_schemas():
6583
def example_array_schemas():
6684
"""Demonstrate array schema conversion."""
6785
print("=== Array Schemas ===")
68-
86+
6987
# Simple array
7088
simple_array = Schema([str])
7189
print("Simple String Array:")
7290
print(json.dumps(simple_array.to_json_schema(), indent=2))
7391
print()
74-
92+
7593
# Mixed array with exact sequence
7694
exact_sequence = Schema(ExactSequence([str, int, bool]))
7795
print("Exact Sequence [str, int, bool]:")
7896
print(json.dumps(exact_sequence.to_json_schema(), indent=2))
7997
print()
80-
98+
8199
# Set (unique items)
82100
unique_strings = Schema({str})
83101
print("Set of Strings (unique items):")
@@ -88,7 +106,7 @@ def example_array_schemas():
88106
def example_validators():
89107
"""Demonstrate validator conversion."""
90108
print("=== Validators ===")
91-
109+
92110
validators = {
93111
"Range": Schema(Range(min=1, max=100)),
94112
"Length": Schema(All(str, Length(min=2, max=50))),
@@ -98,9 +116,9 @@ def example_validators():
98116
"DateTime": Schema(Datetime()),
99117
"Pattern": Schema(Match(r'^[A-Z][a-z]+$')),
100118
"Enum": Schema(In(['red', 'green', 'blue'])),
101-
"Coerce": Schema(Coerce(int))
119+
"Coerce": Schema(Coerce(int)),
102120
}
103-
121+
104122
for name, schema in validators.items():
105123
json_schema = schema.to_json_schema()
106124
print(f"{name}:")
@@ -111,13 +129,13 @@ def example_validators():
111129
def example_composite_validators():
112130
"""Demonstrate composite validator conversion."""
113131
print("=== Composite Validators ===")
114-
132+
115133
# All validator (must pass all conditions)
116134
all_validator = Schema(All(str, Length(min=1), Match(r'^[a-zA-Z]+$')))
117135
print("All(str, Length(min=1), Match('^[a-zA-Z]+$')):")
118136
print(json.dumps(all_validator.to_json_schema(), indent=2))
119137
print()
120-
138+
121139
# Any validator (must pass at least one condition)
122140
any_validator = Schema(Any(str, int, bool))
123141
print("Any(str, int, bool):")
@@ -128,37 +146,41 @@ def example_composite_validators():
128146
def example_complex_schema():
129147
"""Demonstrate a complex, real-world schema."""
130148
print("=== Complex Real-World Schema ===")
131-
149+
132150
# API configuration schema
133-
api_config_schema = Schema({
134-
Required('api'): {
135-
Required('name'): All(str, Length(min=1, max=100)),
136-
Required('version'): Match(r'^\d+\.\d+\.\d+$'),
137-
Required('endpoints'): [{
138-
Required('path'): All(str, Match(r'^/[a-zA-Z0-9/_-]*$')),
139-
Required('method'): In(['GET', 'POST', 'PUT', 'DELETE', 'PATCH']),
140-
Optional('auth_required', default=True): bool,
141-
Optional('rate_limit'): Range(min=1, max=10000),
142-
Optional('description'): All(str, Length(max=500))
143-
}],
144-
Optional('database'): {
145-
Required('host'): str,
146-
Required('port'): Range(min=1, max=65535),
147-
Required('name'): All(str, Length(min=1, max=64)),
148-
Optional('ssl', default=True): bool,
149-
Optional('timeout', default=30): Range(min=1, max=300)
150-
}
151-
},
152-
Optional('logging'): {
153-
'level': In(['DEBUG', 'INFO', 'WARNING', 'ERROR']),
154-
'format': str,
155-
'file': str
156-
},
157-
Optional('features'): {
158-
str: bool # Feature flags
151+
api_config_schema = Schema(
152+
{
153+
Required('api'): {
154+
Required('name'): All(str, Length(min=1, max=100)),
155+
Required('version'): Match(r'^\d+\.\d+\.\d+$'),
156+
Required('endpoints'): [
157+
{
158+
Required('path'): All(str, Match(r'^/[a-zA-Z0-9/_-]*$')),
159+
Required('method'): In(
160+
['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
161+
),
162+
Optional('auth_required', default=True): bool,
163+
Optional('rate_limit'): Range(min=1, max=10000),
164+
Optional('description'): All(str, Length(max=500)),
165+
}
166+
],
167+
Optional('database'): {
168+
Required('host'): str,
169+
Required('port'): Range(min=1, max=65535),
170+
Required('name'): All(str, Length(min=1, max=64)),
171+
Optional('ssl', default=True): bool,
172+
Optional('timeout', default=30): Range(min=1, max=300),
173+
},
174+
},
175+
Optional('logging'): {
176+
'level': In(['DEBUG', 'INFO', 'WARNING', 'ERROR']),
177+
'format': str,
178+
'file': str,
179+
},
180+
Optional('features'): {str: bool}, # Feature flags
159181
}
160-
})
161-
182+
)
183+
162184
json_schema = api_config_schema.to_json_schema()
163185
print("API Configuration Schema:")
164186
print(json.dumps(json_schema, indent=2))
@@ -168,38 +190,40 @@ def example_complex_schema():
168190
def example_usage_with_data():
169191
"""Show how the exported schema can validate actual data."""
170192
print("=== Usage Example ===")
171-
193+
172194
# Define a schema
173-
person_schema = Schema({
174-
Required('name'): All(str, Length(min=1, max=100)),
175-
Required('email'): Email(),
176-
Optional('age'): Range(min=0, max=150),
177-
Optional('tags'): [str]
178-
})
179-
195+
person_schema = Schema(
196+
{
197+
Required('name'): All(str, Length(min=1, max=100)),
198+
Required('email'): Email(),
199+
Optional('age'): Range(min=0, max=150),
200+
Optional('tags'): [str],
201+
}
202+
)
203+
180204
# Export to JSON Schema
181205
json_schema = person_schema.to_json_schema()
182-
206+
183207
# Sample data that would be valid
184208
sample_data = {
185209
"name": "John Doe",
186210
"email": "john@example.com",
187211
"age": 30,
188-
"tags": ["developer", "python"]
212+
"tags": ["developer", "python"],
189213
}
190-
214+
191215
print("Voluptuous Schema:")
192216
print(f"Schema: {person_schema}")
193217
print()
194-
218+
195219
print("Exported JSON Schema:")
196220
print(json.dumps(json_schema, indent=2))
197221
print()
198-
222+
199223
print("Sample Valid Data:")
200224
print(json.dumps(sample_data, indent=2))
201225
print()
202-
226+
203227
# Validate with voluptuous
204228
try:
205229
validated = person_schema(sample_data)
@@ -214,15 +238,15 @@ def main():
214238
print("Voluptuous JSON Schema Export Examples")
215239
print("=" * 50)
216240
print()
217-
241+
218242
example_basic_types()
219243
example_object_schemas()
220244
example_array_schemas()
221245
example_validators()
222246
example_composite_validators()
223247
example_complex_schema()
224248
example_usage_with_data()
225-
249+
226250
print("=" * 50)
227251
print("Examples completed!")
228252
print()

voluptuous/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,12 +74,13 @@
7474
True
7575
"""
7676

77+
from voluptuous.json_schema import to_json_schema
78+
7779
# flake8: noqa
7880
# fmt: off
7981
from voluptuous.schema_builder import *
8082
from voluptuous.util import *
8183
from voluptuous.validators import *
82-
from voluptuous.json_schema import to_json_schema
8384

8485
from voluptuous.error import * # isort: skip
8586

0 commit comments

Comments
 (0)