Compare commits
No commits in common. "9a407495f8106e87ca3d8b69e355872fa573c985" and "fd6df38cdfaa41e5afc014ac5eefd8fd5cae5d98" have entirely different histories.
9a407495f8
...
fd6df38cdf
@ -26,7 +26,7 @@ class TestMiddleware(SpiderwebMiddleware):
|
|||||||
|
|
||||||
Middleware is run twice: once for the incoming request and once for the outgoing response. You only need to include whichever function is required for the functionality you need.
|
Middleware is run twice: once for the incoming request and once for the outgoing response. You only need to include whichever function is required for the functionality you need.
|
||||||
|
|
||||||
## process_request(self, request: Request) -> Optional[HttpResponse]:
|
## process_request(self, request):
|
||||||
|
|
||||||
`process_request` is called before the view is reached in the execution order. You will receive the assembled Request object, and any middleware declared above this one will have already run. Because the request is the single instantiation of a class, you can modify it in-place without returning anything and your changes will stick.
|
`process_request` is called before the view is reached in the execution order. You will receive the assembled Request object, and any middleware declared above this one will have already run. Because the request is the single instantiation of a class, you can modify it in-place without returning anything and your changes will stick.
|
||||||
|
|
||||||
@ -45,67 +45,16 @@ class JohnMiddleware(SpiderwebMiddleware):
|
|||||||
|
|
||||||
In this case, if the user John tries to access any route that starts with "/admin", he'll immediately get denied and the view will never be called. If the request does not have a user attached to it (or the user is not John), then the middleware will return None and Spiderweb will continue processing.
|
In this case, if the user John tries to access any route that starts with "/admin", he'll immediately get denied and the view will never be called. If the request does not have a user attached to it (or the user is not John), then the middleware will return None and Spiderweb will continue processing.
|
||||||
|
|
||||||
## process_response(self, request: Request, response: HttpResponse) -> None:
|
## process_response(self, request, response):
|
||||||
|
|
||||||
This function is called after the view has run and returned a response. You will receive the request object and the response object; like with the request object, the response is also a single instantiation of a class, so any changes you make will stick automatically.
|
This function is called after the view has run and returned a response. You will receive the request object and the response object; like with the request object, the response is also a single instantiation of a class, so any changes you make will stick automatically.
|
||||||
|
|
||||||
Unlike `process_request`, returning a value here doesn't change anything. We're already processing a request, and there are opportunities to turn away requests / change the response at both the `process_request` layer and the view layer, so Spiderweb assumes that whatever it is working on here is what you mean to return to the user. The response object that you receive in the middleware is still prerendered, so any changes you make to it will take effect after it finishes the middleware and renders the response.
|
Unlike `process_request`, returning a value here doesn't change anything. We're already processing a request, and there are opportunities to turn away requests / change the response at both the `process_request` layer and the view layer, so Spiderweb assumes that whatever it is working on here is what you mean to return to the user. The response object that you receive in the middleware is still prerendered, so any changes you make to it will take effect after it finishes the middleware and renders the response.
|
||||||
|
|
||||||
## on_error(self, request: Request, triggered_exception: Exception) -> Optional[HttpResponse]:
|
## on_error(self, request, triggered_exception):
|
||||||
|
|
||||||
This is a helper function that is available for you to override; it's not often used by middleware, but there are some ([like the pydantic middleware](pydantic.md)) that call `on_error` when there is a validation failure.
|
This is a helper function that is available for you to override; it's not often used by middleware, but there are some ([like the pydantic middleware](pydantic.md)) that call `on_error` when there is a validation failure.
|
||||||
|
|
||||||
## post_process(self, request: Request, rendered_response: str) -> str:
|
|
||||||
|
|
||||||
> New in 1.3.0!
|
|
||||||
|
|
||||||
After `process_request` and `process_response` run, the response is rendered out into the raw text that is going to be sent to the client. Right before that happens, `post_process` is called on each middleware in the same order as `process_response` (so the closer something is to the beginning of the middleware list, the more important it is).
|
|
||||||
|
|
||||||
Note that this function *must* return something. Each invocation of `post_process` overwrites the entire output of the response, so make sure to return everything that you want to send. For example, here's a middleware that ~~breaks~~ adjusts the capitalization of the response and also demonstrates passing variables into the middleware:
|
|
||||||
|
|
||||||
```python
|
|
||||||
import random
|
|
||||||
|
|
||||||
from spiderweb.request import Request
|
|
||||||
from spiderweb.middleware import SpiderwebMiddleware
|
|
||||||
from spiderweb.exceptions import ConfigError
|
|
||||||
|
|
||||||
|
|
||||||
class CaseTransformMiddleware(SpiderwebMiddleware):
|
|
||||||
# this breaks everything, but it's hilarious so it's worth it.
|
|
||||||
# Blame Sam.
|
|
||||||
def post_process(self, request: Request, rendered_response: str) -> str:
|
|
||||||
valid_options = ["spongebob", "random"]
|
|
||||||
# grab the value from the extra data passed into the server object
|
|
||||||
# during instantiation
|
|
||||||
method = self.server.extra_data.get("case_transform_middleware_type", "spongebob")
|
|
||||||
if method not in valid_options:
|
|
||||||
raise ConfigError(
|
|
||||||
f"Invalid method '{method}' for CaseTransformMiddleware."
|
|
||||||
f" Valid options are {', '.join(valid_options)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if method == "spongebob":
|
|
||||||
return "".join(
|
|
||||||
char.upper()
|
|
||||||
if i % 2 == 0
|
|
||||||
else char.lower() for i, char in enumerate(rendered_response)
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return "".join(
|
|
||||||
char.upper()
|
|
||||||
if random.random() > 0.5
|
|
||||||
else char for char in rendered_response
|
|
||||||
)
|
|
||||||
|
|
||||||
# usage:
|
|
||||||
|
|
||||||
app = SpiderwebRouter(
|
|
||||||
middleware=["CaseTransformMiddleware"],
|
|
||||||
case_transform_middleware_type="random",
|
|
||||||
)
|
|
||||||
```
|
|
||||||
|
|
||||||
## checks
|
## checks
|
||||||
|
|
||||||
If you want to have runtime verifications that ensure that everything is running smoothly, you can take advantage of Spiderweb's `checks` feature.
|
If you want to have runtime verifications that ensure that everything is running smoothly, you can take advantage of Spiderweb's `checks` feature.
|
||||||
@ -160,4 +109,4 @@ List as many checks as you need there, and the server will run all of them durin
|
|||||||
from spiderweb.exceptions import UnusedMiddleware
|
from spiderweb.exceptions import UnusedMiddleware
|
||||||
```
|
```
|
||||||
|
|
||||||
If you don't want your middleware to run for some reason, `process_request`, `process_response` and `post_process` can all raise the UnusedMiddleware exception. If this happens, Spiderweb will kick your middleware out of the processing order for the rest of the life of the server. Note that this applies to the middleware as a whole, so all functions in the middleware will not be run if an UnusedMiddleware is raised. This is a great way to mark debug middleware that shouldn't run or create time-delay middleware that runs until a certain condition is met!
|
If you don't want your middleware to run for some reason, either `process_request` or `process_response` can raise the UnusedMiddleware exception. If this happens, Spiderweb will kick your middleware out of the processing order for the rest of the life of the server. Note that this applies to the middleware as a whole, so both functions will not be run if an UnusedMiddleware is raised. This is a great way to mark debug middleware that shouldn't run or create time-delay middleware that runs until a certain condition is met!
|
||||||
|
@ -22,14 +22,12 @@ app = SpiderwebRouter(
|
|||||||
"example_middleware.RedirectMiddleware",
|
"example_middleware.RedirectMiddleware",
|
||||||
"spiderweb.middleware.pydantic.PydanticMiddleware",
|
"spiderweb.middleware.pydantic.PydanticMiddleware",
|
||||||
"example_middleware.ExplodingMiddleware",
|
"example_middleware.ExplodingMiddleware",
|
||||||
# "example_middleware.CaseTransformMiddleware",
|
|
||||||
],
|
],
|
||||||
staticfiles_dirs=["static_files"],
|
staticfiles_dirs=["static_files"],
|
||||||
append_slash=False, # default
|
append_slash=False, # default
|
||||||
cors_allow_all_origins=True,
|
cors_allow_all_origins=True,
|
||||||
static_url="static_stuff",
|
static_url="static_stuff",
|
||||||
debug=True,
|
debug=True,
|
||||||
case_transform_middleware_type="spongebob",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,6 +1,3 @@
|
|||||||
import random
|
|
||||||
|
|
||||||
from spiderweb import ConfigError
|
|
||||||
from spiderweb.exceptions import UnusedMiddleware
|
from spiderweb.exceptions import UnusedMiddleware
|
||||||
from spiderweb.middleware import SpiderwebMiddleware
|
from spiderweb.middleware import SpiderwebMiddleware
|
||||||
from spiderweb.request import Request
|
from spiderweb.request import Request
|
||||||
@ -27,25 +24,3 @@ class RedirectMiddleware(SpiderwebMiddleware):
|
|||||||
class ExplodingMiddleware(SpiderwebMiddleware):
|
class ExplodingMiddleware(SpiderwebMiddleware):
|
||||||
def process_request(self, request: Request) -> HttpResponse | None:
|
def process_request(self, request: Request) -> HttpResponse | None:
|
||||||
raise UnusedMiddleware("Unfinished!")
|
raise UnusedMiddleware("Unfinished!")
|
||||||
|
|
||||||
|
|
||||||
class CaseTransformMiddleware(SpiderwebMiddleware):
|
|
||||||
# this breaks everything, but it's hilarious so it's worth it.
|
|
||||||
# Blame Sam.
|
|
||||||
def post_process(self, request: Request, rendered_response: str) -> str:
|
|
||||||
valid_options = ["spongebob", "random"]
|
|
||||||
method = self.server.extra_data.get("case_transform_middleware_type", "spongebob")
|
|
||||||
if method not in valid_options:
|
|
||||||
raise ConfigError(
|
|
||||||
f"Invalid method '{method}' for CaseTransformMiddleware."
|
|
||||||
f" Valid options are {', '.join(valid_options)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if method == "spongebob":
|
|
||||||
return "".join(
|
|
||||||
char.upper() if i % 2 == 0 else char.lower() for i, char in enumerate(rendered_response)
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
return "".join(
|
|
||||||
char.upper() if random.random() > 0.5 else char for char in rendered_response
|
|
||||||
)
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
name = "spiderweb-framework"
|
name = "spiderweb-framework"
|
||||||
version = "1.3.0"
|
version = "1.2.1"
|
||||||
description = "A small web framework, just big enough for a spider."
|
description = "A small web framework, just big enough for a spider."
|
||||||
authors = ["Joe Kaufeld <opensource@joekaufeld.com>"]
|
authors = ["Joe Kaufeld <opensource@joekaufeld.com>"]
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
|
@ -2,7 +2,7 @@ from peewee import DatabaseProxy
|
|||||||
|
|
||||||
DEFAULT_ALLOWED_METHODS = ["POST", "GET", "PUT", "PATCH", "DELETE"]
|
DEFAULT_ALLOWED_METHODS = ["POST", "GET", "PUT", "PATCH", "DELETE"]
|
||||||
DEFAULT_ENCODING = "UTF-8"
|
DEFAULT_ENCODING = "UTF-8"
|
||||||
__version__ = "1.3.0"
|
__version__ = "1.2.1"
|
||||||
|
|
||||||
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
|
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
|
||||||
REGEX_COOKIE_NAME = r"^[a-zA-Z0-9\s\(\)<>@,;:\/\\\[\]\?=\{\}\"\t]*$"
|
REGEX_COOKIE_NAME = r"^[a-zA-Z0-9\s\(\)<>@,;:\/\\\[\]\?=\{\}\"\t]*$"
|
||||||
|
@ -221,19 +221,18 @@ class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixi
|
|||||||
start_response(status, headers)
|
start_response(status, headers)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
rendered_output: str = resp.render()
|
rendered_output = resp.render()
|
||||||
final_output: str | list[str] = self.post_process_middleware(request, rendered_output)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.log.error("Fatal error!")
|
self.log.error("Fatal error!")
|
||||||
self.log.error(e)
|
self.log.error(e)
|
||||||
self.log.error(traceback.format_exc())
|
self.log.error(traceback.format_exc())
|
||||||
return [f"Internal Server Error: {e}".encode(DEFAULT_ENCODING)]
|
return [f"Internal Server Error: {e}".encode(DEFAULT_ENCODING)]
|
||||||
|
|
||||||
if not isinstance(final_output, list):
|
if not isinstance(rendered_output, list):
|
||||||
final_output = [final_output]
|
rendered_output = [rendered_output]
|
||||||
encoded_resp = [
|
encoded_resp = [
|
||||||
chunk.encode(DEFAULT_ENCODING) if isinstance(chunk, str) else chunk
|
chunk.encode(DEFAULT_ENCODING) if isinstance(chunk, str) else chunk
|
||||||
for chunk in final_output
|
for chunk in rendered_output
|
||||||
]
|
]
|
||||||
|
|
||||||
return encoded_resp
|
return encoded_resp
|
||||||
|
@ -60,14 +60,3 @@ class MiddlewareMixin:
|
|||||||
except UnusedMiddleware:
|
except UnusedMiddleware:
|
||||||
self.middleware.remove(middleware)
|
self.middleware.remove(middleware)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
def post_process_middleware(self, request: Request, response: str) -> str:
|
|
||||||
# run them in reverse order, same as process_response. The top of the middleware
|
|
||||||
# stack should be the first and last middleware to run.
|
|
||||||
for middleware in reversed(self.middleware):
|
|
||||||
try:
|
|
||||||
response = middleware.post_process(request, response)
|
|
||||||
except UnusedMiddleware:
|
|
||||||
self.middleware.remove(middleware)
|
|
||||||
continue
|
|
||||||
return response
|
|
||||||
|
@ -9,8 +9,6 @@ class SpiderwebMiddleware:
|
|||||||
|
|
||||||
process_request(self, request) -> None or Response
|
process_request(self, request) -> None or Response
|
||||||
process_response(self, request, resp) -> None
|
process_response(self, request, resp) -> None
|
||||||
on_error(self, request, e) -> Response
|
|
||||||
post_process(self, request, resp) -> Response
|
|
||||||
|
|
||||||
Middleware can be used to modify requests and responses in a variety of ways.
|
Middleware can be used to modify requests and responses in a variety of ways.
|
||||||
If one of the two methods is not defined, the request or resp will be passed
|
If one of the two methods is not defined, the request or resp will be passed
|
||||||
@ -24,26 +22,12 @@ class SpiderwebMiddleware:
|
|||||||
self.server = server
|
self.server = server
|
||||||
|
|
||||||
def process_request(self, request: Request) -> HttpResponse | None:
|
def process_request(self, request: Request) -> HttpResponse | None:
|
||||||
# This method is called before the request is passed to the view. You can safely
|
|
||||||
# modify the request in this method, or return an HttpResponse to short-circuit
|
|
||||||
# the request and return a response immediately.
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def process_response(
|
def process_response(
|
||||||
self, request: Request, response: HttpResponse
|
self, request: Request, response: HttpResponse
|
||||||
) -> None:
|
) -> HttpResponse | None:
|
||||||
# This method is called after the view has returned a response. You can modify
|
|
||||||
# the response in this method. The response will be returned to the client after
|
|
||||||
# all middleware has been processed.
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def on_error(self, request: Request, e: Exception) -> HttpResponse | None:
|
def on_error(self, request: Request, e: Exception) -> HttpResponse | None:
|
||||||
# This method is called if an exception is raised during the request. You can
|
|
||||||
# return a response here to handle the error. If you return None, the exception
|
|
||||||
# will be re-raised.
|
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def post_process(self, request: Request, rendered_response: str) -> str:
|
|
||||||
# This method is called after all the middleware has been processed and receives
|
|
||||||
# the final rendered response in str form. You can modify the response here.
|
|
||||||
return rendered_response
|
|
||||||
|
@ -16,8 +16,3 @@ class ExplodingResponseMiddleware(SpiderwebMiddleware):
|
|||||||
class InterruptingMiddleware(SpiderwebMiddleware):
|
class InterruptingMiddleware(SpiderwebMiddleware):
|
||||||
def process_request(self, request: Request) -> HttpResponse:
|
def process_request(self, request: Request) -> HttpResponse:
|
||||||
return HttpResponse("Moo!")
|
return HttpResponse("Moo!")
|
||||||
|
|
||||||
|
|
||||||
class PostProcessingMiddleware(SpiderwebMiddleware):
|
|
||||||
def post_process(self, request: Request, response: str) -> str:
|
|
||||||
return response + " Moo!"
|
|
||||||
|
@ -298,22 +298,6 @@ def test_csrf_trusted_origins():
|
|||||||
assert resp2 == '{"name": "bob"}'
|
assert resp2 == '{"name": "bob"}'
|
||||||
|
|
||||||
|
|
||||||
def test_post_process_middleware():
|
|
||||||
app, environ, start_response = setup(
|
|
||||||
middleware=[
|
|
||||||
"spiderweb.tests.middleware.PostProcessingMiddleware",
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
app.add_route("/", text_view)
|
|
||||||
|
|
||||||
environ["HTTP_USER_AGENT"] = "hi"
|
|
||||||
environ["REMOTE_ADDR"] = "/"
|
|
||||||
environ["REQUEST_METHOD"] = "GET"
|
|
||||||
|
|
||||||
assert app(environ, start_response) == [bytes("Hi! Moo!", DEFAULT_ENCODING)]
|
|
||||||
|
|
||||||
|
|
||||||
class TestCorsMiddleware:
|
class TestCorsMiddleware:
|
||||||
# adapted from:
|
# adapted from:
|
||||||
# https://github.com/adamchainz/django-cors-headers/blob/main/tests/test_middleware.py
|
# https://github.com/adamchainz/django-cors-headers/blob/main/tests/test_middleware.py
|
||||||
|
Loading…
Reference in New Issue
Block a user