99from webspark .contrib .plugins .schema import SchemaPlugin
1010from webspark .core import View , WebSpark , path
1111from webspark .http import Context
12- from webspark .schema import (
13- BooleanField ,
14- EmailField ,
15- IntegerField ,
16- Schema ,
17- StringField ,
18- )
1912from webspark .utils import HTTPException
2013from webspark .utils .decorators import apply
14+ from webspark .validation import Schema , fields
2115
2216
2317# Define a schema for user data
2418class UserSchema (Schema ):
25- name = StringField (required = True , max_length = 100 )
26- email = EmailField (required = True )
27- age = IntegerField (min_value = 1 , max_value = 120 )
28- is_active = BooleanField (default = True )
19+ name = fields . StringField (required = True , max_length = 100 )
20+ email = fields . EmailField (required = True )
21+ age = fields . IntegerField (min_value = 1 , max_value = 120 )
22+ is_active = fields . BooleanField (default = True )
2923
3024
3125# In-memory storage
@@ -36,23 +30,17 @@ class UserSchema(Schema):
3630class UserView (View ):
3731 """Handle user operations with schema validation."""
3832
39- body_schema = UserSchema # Attach the schema for automatic validation
40-
4133 def handle_get (self , ctx : Context ):
4234 """Return all users."""
4335 ctx .json ({"users" : users })
4436
4537 @apply (
46- SchemaPlugin (UserSchema , prop = "body" , kw = "body" ),
38+ SchemaPlugin (UserSchema , prop = "body" ),
4739 )
4840 def handle_post (self , ctx : Context , body : dict ):
4941 """Create a new user with validation."""
5042 global next_id
5143
52- # When body_schema is defined, WebSpark automatically validates the request body
53- # and makes the validated data available through self.validated_body()
54- # validated_data, errors = self.validated_body(raise_=True)
55-
5644 # Create new user with validated data
5745 new_user = {
5846 "id" : next_id ,
@@ -95,5 +83,5 @@ def handle_get(self, ctx: Context):
9583if __name__ == "__main__" :
9684 # For development purposes, you can run this with a WSGI server like:
9785 # gunicorn examples.schema_example:app
98- print ("Schema Validation Example" )
86+ print ("Schema Plugin Example" )
9987 print ("Run with: gunicorn examples.schema_plugin_example:app" )
0 commit comments