Skip to content

Commit bc579e8

Browse files
committed
Updated example for redirects
1 parent 4ef72f1 commit bc579e8

File tree

2 files changed

+26
-5
lines changed

2 files changed

+26
-5
lines changed

docs/examples.rst

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -262,10 +262,13 @@ Sometimes you might want to redirect the user to a different URL, either on the
262262
You can do that by returning ``Redirect`` from your handler function.
263263

264264
You can specify wheter the redirect is permanent or temporary by passing ``permanent=...`` to ``Redirect``.
265+
If you need the redirect to preserve the original request method, you can set ``preserve_method=True``.
266+
267+
Alternatively, you can pass a ``status`` object directly to ``Redirect`` constructor.
265268

266269
.. literalinclude:: ../examples/httpserver_redirects.py
267270
:caption: examples/httpserver_redirects.py
268-
:emphasize-lines: 14-18,26,38
271+
:emphasize-lines: 22-26,32,38,44,56
269272
:linenos:
270273

271274
Server-Sent Events

examples/httpserver_redirects.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,15 @@
55
import socketpool
66
import wifi
77

8-
from adafruit_httpserver import Server, Request, Response, Redirect, NOT_FOUND_404
8+
from adafruit_httpserver import (
9+
Server,
10+
Request,
11+
Response,
12+
Redirect,
13+
POST,
14+
NOT_FOUND_404,
15+
MOVED_PERMANENTLY_301,
16+
)
917

1018

1119
pool = socketpool.SocketPool(wifi.radio)
@@ -20,12 +28,22 @@
2028

2129
@server.route("/blinka")
2230
def redirect_blinka(request: Request):
23-
"""
24-
Always redirect to a Blinka page as permanent redirect.
25-
"""
31+
"""Always redirect to a Blinka page as permanent redirect."""
2632
return Redirect(request, "https://circuitpython.org/blinka", permanent=True)
2733

2834

35+
@server.route("/adafruit")
36+
def redirect_adafruit(request: Request):
37+
"""Permanent redirect to Adafruit website with explicitly set status code."""
38+
return Redirect(request, "https://www.adafruit.com/", status=MOVED_PERMANENTLY_301)
39+
40+
41+
@server.route("/login", POST)
42+
def temporary_login_redirect(request: Request):
43+
"""Temporary moved login page with preserved POST data."""
44+
return Redirect(request, "https://circuitpython.org/blinka", preserve_method=True)
45+
46+
2947
@server.route("/<slug>")
3048
def redirect_other(request: Request, slug: str = None):
3149
"""

0 commit comments

Comments
 (0)