7
7
import socketpool
8
8
import wifi
9
9
10
- from adafruit_httpserver import Server , Route , Request , Response , GET , POST
10
+ from adafruit_httpserver import Server , Route , as_route , Request , Response , GET , POST
11
11
12
12
13
13
pool = socketpool .SocketPool (wifi .radio )
16
16
pixel = neopixel .NeoPixel (board .NEOPIXEL , 1 )
17
17
18
18
19
+ # This is the simplest way to register a route. It uses the Server object in current scope.
19
20
@server .route ("/change-neopixel-color" , GET )
20
21
def change_neopixel_color_handler_query_params (request : Request ):
21
22
"""Changes the color of the built-in NeoPixel using query/GET params."""
@@ -31,7 +32,9 @@ def change_neopixel_color_handler_query_params(request: Request):
31
32
return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
32
33
33
34
34
- @server .route ("/change-neopixel-color" , POST )
35
+ # This is another way to register a route. It uses the decorator that converts the function into
36
+ # a Route object that can be imported and registered later.
37
+ @as_route ("/change-neopixel-color" , POST )
35
38
def change_neopixel_color_handler_post_body (request : Request ):
36
39
"""Changes the color of the built-in NeoPixel using POST body."""
37
40
@@ -54,6 +57,13 @@ def change_neopixel_color_handler_post_json(request: Request):
54
57
return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
55
58
56
59
60
+ # You can always manually create a Route object and import or register it later.
61
+ # Using this approach you can also use the same handler for multiple routes.
62
+ post_json_route = Route (
63
+ "/change-neopixel-color/json" , GET , change_neopixel_color_handler_post_json
64
+ )
65
+
66
+
57
67
def change_neopixel_color_handler_url_params (
58
68
request : Request , r : str = "0" , g : str = "0" , b : str = "0"
59
69
):
@@ -66,17 +76,17 @@ def change_neopixel_color_handler_url_params(
66
76
return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
67
77
68
78
69
- url_params_route = Route (
70
- "/change-neopixel-color/<r>/<g>/<b>" , GET , change_neopixel_color_handler_url_params
71
- )
72
-
73
- # Alternative way of registering routes.
79
+ # Registering Route objects
74
80
server .add_routes (
75
81
[
82
+ change_neopixel_color_handler_post_body ,
83
+ post_json_route ,
84
+ # You can also register a inline created Route object
76
85
Route (
77
- "/change-neopixel-color/json" , GET , change_neopixel_color_handler_post_json
86
+ path = "/change-neopixel-color/<r>/<g>/<b>" ,
87
+ methods = GET ,
88
+ handler = change_neopixel_color_handler_url_params ,
78
89
),
79
- url_params_route ,
80
90
]
81
91
)
82
92
0 commit comments