📝 layout and start of middleware

This commit is contained in:
Joe Kaufeld 2024-08-27 09:09:05 -04:00
parent fe9927f54e
commit 0cc8e76aec
9 changed files with 26 additions and 6 deletions

View File

@ -1,6 +1,8 @@
- [home](README.md) - [home](README.md)
- [quickstart](quickstart.md) - [quickstart](quickstart.md)
- [responses](responses.md) - [responses](responses.md)
- Middleware - middleware
- [middleware](middleware/test.md) - [overview](middleware/overview.md)
- [middleware2](middleware/test2.md) - [csrf](middleware/csrf.md)
- [pydantic](middleware/pydantic.md)
- [session](middleware/sessions.md)

0
docs/middleware/csrf.md Normal file
View File

View File

@ -0,0 +1,19 @@
# middleware
When processing a request, there are often things that need to happen before the request is passed to the view. Middleware is a way to intercept the request and response objects and do something with them before they are passed to the view or returned to the client.
Middleware in Spiderweb is defined as a list of importable strings that looks like this:
```python
from spiderweb import SpiderwebRouter
app = SpiderwebRouter(
middleware=[
"spiderweb.middleware.sessions.SessionMiddleware",
"spiderweb.middleware.csrf.CSRFMiddleware",
"spiderweb.middleware.pydantic.PydanticMiddleware",
],
)
```
Middleware affects both the incoming request AND the outgoing response, so the order that it's defined here is important. When a request comes in, it will be processed through the middleware in the order that it's defined, but after the response is created, it will pass back through the middleware going the opposite direction.

View File

View File

View File

@ -1 +0,0 @@
asdf

View File

@ -1 +0,0 @@
asdfawaasdf

View File

@ -39,6 +39,7 @@ logging.basicConfig(level=logging.INFO)
class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixin): class SpiderwebRouter(LocalServerMixin, MiddlewareMixin, RoutesMixin, FernetMixin):
def __init__( def __init__(
self, self,
*,
addr: str = None, addr: str = None,
port: int = None, port: int = None,
db: Optional[Database] = None, db: Optional[Database] = None,

View File

@ -39,7 +39,7 @@ class MiddlewareMixin:
def process_response_middleware( def process_response_middleware(
self, request: Request, response: HttpResponse self, request: Request, response: HttpResponse
) -> None: ) -> None:
for middleware in self.middleware: for middleware in reversed(self.middleware):
try: try:
middleware.process_response(request, response) middleware.process_response(request, response)
except UnusedMiddleware: except UnusedMiddleware: