77import socketpool
88import wifi
99
10- from adafruit_httpserver import Server , Route , Request , Response , GET , POST
10+ from adafruit_httpserver import Server , Route , as_route , Request , Response , GET , POST
1111
1212
1313pool = socketpool .SocketPool (wifi .radio )
1616pixel = neopixel .NeoPixel (board .NEOPIXEL , 1 )
1717
1818
19+ # This is the simplest way to register a route. It uses the Server object in current scope.
1920@server .route ("/change-neopixel-color" , GET )
2021def change_neopixel_color_handler_query_params (request : Request ):
2122 """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):
3132 return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
3233
3334
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 )
3538def change_neopixel_color_handler_post_body (request : Request ):
3639 """Changes the color of the built-in NeoPixel using POST body."""
3740
@@ -54,6 +57,13 @@ def change_neopixel_color_handler_post_json(request: Request):
5457 return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
5558
5659
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+
5767def change_neopixel_color_handler_url_params (
5868 request : Request , r : str = "0" , g : str = "0" , b : str = "0"
5969):
@@ -66,17 +76,17 @@ def change_neopixel_color_handler_url_params(
6676 return Response (request , f"Changed NeoPixel to color ({ r } , { g } , { b } )" )
6777
6878
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
7480server .add_routes (
7581 [
82+ change_neopixel_color_handler_post_body ,
83+ post_json_route ,
84+ # You can also register a inline created Route object
7685 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 ,
7889 ),
79- url_params_route ,
8090 ]
8191)
8292
0 commit comments