Compare commits

..

No commits in common. "aabe20cff76c08a78fddabc3c974a918b05426af" and "d4f8109663f25cf5de96679314648c6581ff5da1" have entirely different histories.

5 changed files with 12 additions and 77 deletions

View File

@ -53,10 +53,6 @@ This function is called after the view has run and returned a response. You will
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, 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.
## UnusedMiddleware ## UnusedMiddleware
```python ```python

View File

@ -1,57 +0,0 @@
# pydantic form validation
```python
from spiderweb import SpiderwebRouter
app = SpiderwebRouter(
middleware=["spiderweb.middleware.pydantic.PydanticMiddleware"],
)
```
When working with form data, you may not want to always have to perform your own validation on the incoming data. Spiderweb gives you a way out of the box to perform this validation using Pydantic.
Let's assume that we have a form view that looks like this:
```python
@app.route("/myform", allowed_methods=["GET", "POST"])
def form(request):
if request.method == "POST":
if "username" in request.POST and "comment" in request.POST:
# there's presumably other data in there, but we care about these two
return JsonResponse(
data={
"username": request.POST["username"],
"comment": request.POST["comment"]
}
)
else:
return TemplateResponse(request, "myform.html")
```
Our form takes in an indeterminate amount of data, but if we really care about some of the fields (or all of them) then we can utilize Pydantic to handle this validation for us. Once the middleware is enabled, we can update our view:
```python
from pydantic import EmailStr
from spiderweb.middleware.pydantic import RequestModel
class CommentForm(RequestModel):
email: EmailStr
comment: str
@app.route("/myform", allowed_methods=["GET", "POST"])
def form(request: CommentForm):
if request.method == "POST":
return JsonResponse(request.validated_data.dict())
else:
return TemplateResponse(request, "myform.html")
```
The Pydantic middleware will automatically detect that the model that you want to use for the request has been added as a type hint, and it will run the validation during the middleware phase so that it can return an error immediately if it fails validation.
> [!NOTE]
> Your validator **must** inherit from RequestModel to function correctly! If it doesn't, it will not trigger.
If the validation fails, the middleware will call `on_error`, which by default will return a 400 with a list of the broken fields. You may not want this behavior, so the easiest way to address it is to subclass PydanticMiddleware with your own version and override `on_error` to do whatever you'd like.
If validation succeeds, the data from the validator will appear on the request object under `request.validated_data` — to access it, just call `.dict()` on the validated data.

View File

@ -4,7 +4,9 @@
from spiderweb import SpiderwebRouter from spiderweb import SpiderwebRouter
app = SpiderwebRouter( app = SpiderwebRouter(
middleware=["spiderweb.middleware.sessions.SessionMiddleware"], middleware=[
"spiderweb.middleware.sessions.SessionMiddleware",
],
) )
``` ```
@ -14,7 +16,7 @@ Visitors are assigned a random value when they visit for the first time, and tha
## request.SESSION ## request.SESSION
When the sessions middleware is enabled, the request object will have a new attribute labeled `SESSION`. This is a dictionary, and you can put pretty much anything you want in it as long as it's serializable to JSON! When the user visits again with an active session, the data will automatically be available on the `SESSION` object again. Here's an example of a complete server using sessions: When the sessions middleware is enabled, the request object will have a new attribute labeled `SESSION`. This is a dictionary, and you can put pretty much anything you want in it as long as its serializable to JSON! When the user visits again with an active session, the data will automatically be available on the `SESSION` object again. Here's an example of a complete server using sessions:
```python ```python
from spiderweb import SpiderwebRouter, HttpResponse from spiderweb import SpiderwebRouter, HttpResponse
@ -68,7 +70,7 @@ This marks that the cookie will only be sent back to the server with a valid HTT
### session_cookie_http_only ### session_cookie_http_only
This marks whether the session cookie will have the `HttpOnly` attribute. This makes it unreadable to client-side javascript. The default is `False`. This marks whether the session cookie will have the `HttpOnly` attribute. This makes it invisible to client-side javascript. The default is `False`.
### session_cookie_same_site ### session_cookie_same_site

View File

@ -28,6 +28,3 @@ class SpiderwebMiddleware:
self, request: Request, response: HttpResponse self, request: Request, response: HttpResponse
) -> HttpResponse | None: ) -> HttpResponse | None:
pass pass
def on_error(self, request: Request, e: Exception) -> HttpResponse | None:
pass

View File

@ -1,4 +1,3 @@
import inspect
from typing import get_type_hints from typing import get_type_hints
from pydantic import BaseModel from pydantic import BaseModel
@ -20,15 +19,13 @@ class PydanticMiddleware(SpiderwebMiddleware):
if not request.method == "POST": if not request.method == "POST":
return return
types = get_type_hints(request.handler) types = get_type_hints(request.handler)
# we don't know what the user named the request object, but if "request" not in types:
# we know that it's first in the list, and it's always an arg. return
request_arg_name = inspect.getfullargspec(request.handler).args[0] try:
if types.get(request_arg_name) in RequestModel.__subclasses__(): data = types["request"].parse_obj(request.POST)
try: request.validated_data = data
data = types[request_arg_name].parse_obj(request.POST) except ValidationError as e:
request.validated_data = data return self.on_error(request, e)
except ValidationError as e:
return self.on_error(request, e)
def on_error(self, request: Request, e: ValidationError): def on_error(self, request: Request, e: ValidationError):
# Separated out into its own method so that it can be overridden # Separated out into its own method so that it can be overridden