-
Notifications
You must be signed in to change notification settings - Fork 2
/
example_middleware.py
61 lines (50 loc) · 2.24 KB
/
example_middleware.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import random
from spiderweb import ConfigError
from spiderweb.exceptions import UnusedMiddleware
from spiderweb.middleware import SpiderwebMiddleware
from spiderweb.request import Request
from spiderweb.response import HttpResponse, RedirectResponse
class TestMiddleware(SpiderwebMiddleware):
def process_request(self, request: Request) -> None:
# example of a middleware that sets a flag on the request
request.spiderweb = True
def process_response(self, request: Request, response: HttpResponse) -> None:
# example of a middleware that sets a header on the resp
if hasattr(request, "spiderweb"):
response.headers["X-Spiderweb"] = "true"
class RedirectMiddleware(SpiderwebMiddleware):
def process_request(self, request: Request) -> HttpResponse:
if request.path == "/middleware":
return RedirectResponse("/")
class ExplodingMiddleware(SpiderwebMiddleware):
def process_request(self, request: Request) -> HttpResponse | None:
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, response: HttpResponse, 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":
response.headers["X-Case-Transform"] = "spongebob"
return "".join(
char.upper() if i % 2 == 0 else char.lower()
for i, char in enumerate(rendered_response)
)
else:
response.headers["X-Case-Transform"] = "random"
return "".join(
char.upper() if random.random() > 0.5 else char
for char in rendered_response
)