Skip to content

Commit 78cfa0e

Browse files
committed
Updated examples and added new ones hat present added functionality
1 parent c95290f commit 78cfa0e

4 files changed

Lines changed: 124 additions & 4 deletions

File tree

adafruit_httpserver/server.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,14 +43,18 @@ def route(self, path: str, method: HTTPMethod = HTTPMethod.GET) -> Callable:
4343
"""
4444
Decorator used to add a route.
4545
46-
:param str path: filename path
46+
:param str path: URL path
4747
:param HTTPMethod method: HTTP method: HTTPMethod.GET, HTTPMethod.POST, etc.
4848
4949
Example::
5050
5151
@server.route("/example", HTTPMethod.GET)
5252
def route_func(request):
5353
...
54+
55+
@server.route("/example/<my_parameter>", HTTPMethod.GET)
56+
def route_func(request, my_parameter):
57+
...
5458
"""
5559

5660
def route_decorator(func: Callable) -> Callable:

docs/examples.rst

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ Change NeoPixel color
3636
If you want your code to do more than just serve web pages,
3737
use the start/poll methods as shown in this example.
3838

39-
For example by going to ``/change-neopixel-color?r=255&g=0&b=0`` you can change the color of the NeoPixel to red.
39+
For example by going to ``/change-neopixel-color?r=255&g=0&b=0`` or ``/change-neopixel-color/255/0/0``
40+
you can change the color of the NeoPixel to red.
4041
Tested on ESP32-S2 Feather.
4142

4243
.. literalinclude:: ../examples/httpserver_neopixel.py
@@ -62,3 +63,28 @@ To use it, you need to set the ``chunked=True`` when creating a ``HTTPResponse``
6263
.. literalinclude:: ../examples/httpserver_chunked.py
6364
:caption: examples/httpserver_chunked.py
6465
:linenos:
66+
67+
URL parameters
68+
---------------------
69+
70+
Alternatively to using query parameters, you can use URL parameters.
71+
72+
In order to use URL parameters, you need to wrap them inside ``<>`` in ``HTTPServer.route``, e.g. ``<my_parameter>``.
73+
74+
All URL parameters are passed as positional arguments to the handler function, in order they are specified.
75+
76+
Notice how the handler function in example below accepts two additional arguments : ``device_id`` and ``action``.
77+
78+
If you specify multiple routes for single handler function and they have different number of URL parameters,
79+
make sure to add default values for all the ones that might not be passed.
80+
In the example below the second route has only one URL parameter, so the ``action`` parameter has a default value of ``None``.
81+
82+
Keep in mind that URL parameters are always passed as strings, so you need to convert them to the desired type.
83+
Also note that the names of the function parameters **do not have to match** with the ones used in route, but they **must** be in the same order.
84+
Look at the example below to see how the ``route_param_1`` and ``route_param_1`` are named differently in the handler function.
85+
86+
Although it is possible, it makes more sens be consistent with the names of the parameters in the route and in the handler function.
87+
88+
.. literalinclude:: ../examples/httpserver_url_parameters.py
89+
:caption: examples/httpserver_url_parameters.py
90+
:linenos:

examples/httpserver_neopixel.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@
2828

2929

3030
@server.route("/change-neopixel-color")
31-
def change_neopixel_color_handler(request: HTTPRequest):
31+
def change_neopixel_color_handler_query_params(request: HTTPRequest):
3232
"""
33-
Changes the color of the built-in NeoPixel.
33+
Changes the color of the built-in NeoPixel using query/GET params.
3434
"""
3535
r = request.query_params.get("r")
3636
g = request.query_params.get("g")
@@ -42,5 +42,18 @@ def change_neopixel_color_handler(request: HTTPRequest):
4242
response.send(f"Changed NeoPixel to color ({r}, {g}, {b})")
4343

4444

45+
@server.route("/change-neopixel-color/<r>/<g>/<b>")
46+
def change_neopixel_color_handler_url_params(
47+
request: HTTPRequest, r: str, g: str, b: str
48+
):
49+
"""
50+
Changes the color of the built-in NeoPixel using URL params.
51+
"""
52+
pixel.fill((int(r or 0), int(g or 0), int(b or 0)))
53+
54+
with HTTPResponse(request, content_type=MIMEType.TYPE_TXT) as response:
55+
response.send(f"Changed NeoPixel to color ({r}, {g}, {b})")
56+
57+
4558
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
4659
server.serve_forever(str(wifi.radio.ipv4_address))
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# SPDX-FileCopyrightText: 2022 Dan Halbert for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
import secrets # pylint: disable=no-name-in-module
6+
7+
import socketpool
8+
import wifi
9+
10+
from adafruit_httpserver.mime_type import MIMEType
11+
from adafruit_httpserver.request import HTTPRequest
12+
from adafruit_httpserver.response import HTTPResponse
13+
from adafruit_httpserver.server import HTTPServer
14+
15+
16+
ssid, password = secrets.WIFI_SSID, secrets.WIFI_PASSWORD # pylint: disable=no-member
17+
18+
print("Connecting to", ssid)
19+
wifi.radio.connect(ssid, password)
20+
print("Connected to", ssid)
21+
22+
pool = socketpool.SocketPool(wifi.radio)
23+
server = HTTPServer(pool)
24+
25+
26+
class Device:
27+
def turn_on(self):
28+
raise NotImplementedError
29+
30+
def turn_off(self):
31+
raise NotImplementedError
32+
33+
34+
def get_device(device_id: str) -> Device: # pylint: disable=unused-argument
35+
"""
36+
This is a **made up** function that returns a `Device` object.
37+
"""
38+
return Device()
39+
40+
41+
@server.route("/device/<device_id>/action/<action>")
42+
@server.route("/device/emergency-power-off/<device_id>")
43+
def perform_action(request: HTTPRequest, device_id: str, action: str = None):
44+
"""
45+
Performs an "action" on a specified device.
46+
"""
47+
48+
device = get_device(device_id)
49+
50+
if action == "turn_on":
51+
device.turn_on()
52+
elif action == "turn_off" or action is None:
53+
device.turn_off()
54+
55+
with HTTPResponse(request, content_type=MIMEType.TYPE_TXT) as response:
56+
response.send(f"Action ({action}) performed on device with ID: {device_id}")
57+
58+
59+
@server.route("/something/<route_param_1>/<route_param_2>")
60+
def different_name_parameters(
61+
request: HTTPRequest,
62+
handler_param_1: str, # pylint: disable=unused-argument
63+
handler_param_2: str = None, # pylint: disable=unused-argument
64+
):
65+
"""
66+
Presents that the parameters can be named anything.
67+
68+
``route_param_1`` -> ``handler_param_1``
69+
``route_param_2`` -> ``handler_param_2``
70+
"""
71+
72+
with HTTPResponse(request, content_type=MIMEType.TYPE_TXT) as response:
73+
response.send("200 OK")
74+
75+
76+
print(f"Listening on http://{wifi.radio.ipv4_address}:80")
77+
server.serve_forever(str(wifi.radio.ipv4_address))

0 commit comments

Comments
 (0)