2024-08-09 14:15:32 -04:00
|
|
|
from spiderweb.exceptions import UnusedMiddleware
|
2024-08-09 12:02:46 -04:00
|
|
|
from spiderweb.middleware import SpiderwebMiddleware
|
|
|
|
from spiderweb.request import Request
|
|
|
|
from spiderweb.response import HttpResponse, RedirectResponse
|
|
|
|
|
|
|
|
|
|
|
|
class TestMiddleware(SpiderwebMiddleware):
|
2024-08-14 17:27:21 -04:00
|
|
|
def process_request(self, request: Request) -> None:
|
2024-08-09 12:02:46 -04:00
|
|
|
# example of a middleware that sets a flag on the request
|
|
|
|
request.spiderweb = True
|
|
|
|
|
|
|
|
def process_response(
|
|
|
|
self, request: Request, response: HttpResponse
|
2024-08-14 17:27:21 -04:00
|
|
|
) -> None:
|
2024-08-09 12:02:46 -04:00
|
|
|
# example of a middleware that sets a header on the resp
|
|
|
|
if hasattr(request, "spiderweb"):
|
|
|
|
response.headers["X-Spiderweb"] = "true"
|
|
|
|
|
|
|
|
|
|
|
|
class RedirectMiddleware(SpiderwebMiddleware):
|
2024-08-14 17:27:21 -04:00
|
|
|
def process_request(self, request: Request) -> HttpResponse:
|
2024-08-09 12:02:46 -04:00
|
|
|
if request.path == "/middleware":
|
|
|
|
return RedirectResponse("/")
|
2024-08-09 14:15:32 -04:00
|
|
|
|
|
|
|
|
|
|
|
class ExplodingMiddleware(SpiderwebMiddleware):
|
|
|
|
def process_request(self, request: Request) -> HttpResponse | None:
|
|
|
|
raise UnusedMiddleware("Unfinished!")
|