🐛 fix handling of UnusedMiddleware

This commit is contained in:
Joe Kaufeld 2024-08-09 14:15:32 -04:00
parent a4dc193d01
commit 8e37e58a99
4 changed files with 26 additions and 6 deletions

View File

@ -6,7 +6,8 @@ app = WebServer(
templates_dirs=["templates"],
middleware=[
"example_middleware.TestMiddleware",
"example_middleware.RedirectMiddleware"
"example_middleware.RedirectMiddleware",
"example_middleware.ExplodingMiddleware",
],
append_slash=False # default
)
@ -39,6 +40,11 @@ def middleware(request):
)
@app.route("/example/<int:id>")
def example(request, id):
return HttpResponse(body=f"Example with id {id}")
if __name__ == "__main__":
# can also add routes like this:
# app.add_route("/", index)

View File

@ -1,3 +1,4 @@
from spiderweb.exceptions import UnusedMiddleware
from spiderweb.middleware import SpiderwebMiddleware
from spiderweb.request import Request
from spiderweb.response import HttpResponse, RedirectResponse
@ -20,3 +21,8 @@ class RedirectMiddleware(SpiderwebMiddleware):
def process_request(self, request: Request) -> HttpResponse | None:
if request.path == "/middleware":
return RedirectResponse("/")
class ExplodingMiddleware(SpiderwebMiddleware):
def process_request(self, request: Request) -> HttpResponse | None:
raise UnusedMiddleware("Unfinished!")

View File

@ -1,6 +1,6 @@
[tool.poetry]
name = "spiderweb"
version = "0.1.0"
version = "0.4.0"
description = "A small web framework, just big enough to hold your average spider."
authors = ["Joe Kaufeld <opensource@joekaufeld.com>"]
readme = "README.md"

View File

@ -23,7 +23,7 @@ from spiderweb.exceptions import (
ConfigError,
ParseError,
GeneralException,
NoResponseError,
NoResponseError, UnusedMiddleware,
)
from spiderweb.request import Request
from spiderweb.response import HttpResponse, JsonResponse, TemplateResponse, RedirectResponse
@ -301,7 +301,11 @@ class RequestHandler(BaseHTTPRequestHandler):
def process_request_middleware(self, request: Request) -> None | bool:
for middleware in self.middleware:
resp = middleware.process_request(request)
try:
resp = middleware.process_request(request)
except UnusedMiddleware:
self.middleware.remove(middleware)
continue
if resp:
self.process_response_middleware(request, resp)
self.fire_response(request, resp)
@ -309,7 +313,11 @@ class RequestHandler(BaseHTTPRequestHandler):
def process_response_middleware(self, request: Request, response: HttpResponse) -> None:
for middleware in self.middleware:
middleware.process_response(request, response)
try:
middleware.process_response(request, response)
except UnusedMiddleware:
self.middleware.remove(middleware)
continue
def prepare_response(self, request, resp) -> HttpResponse:
try:
@ -322,7 +330,7 @@ class RequestHandler(BaseHTTPRequestHandler):
for middleware in self.middleware:
middleware.process_response(request, resp)
self.fire_response(resp)
self.fire_response(request, resp)
except APIError:
raise