| 1 |
import time |
| 2 |
from typing import Dict |
| 3 |
|
| 4 |
from litestar import Litestar, WebSocket, get, websocket |
| 5 |
from litestar.datastructures import MutableScopeHeaders |
| 6 |
from litestar.enums import ScopeType |
| 7 |
from litestar.middleware import ASGIMiddleware |
| 8 |
from litestar.types import ASGIApp, Message, Receive, Scope, Send |
| 9 |
|
| 10 |
|
| 11 |
class MyMiddleware(ASGIMiddleware): |
| 12 |
scopes = (ScopeType.HTTP,) |
| 13 |
exclude_path_pattern = ("first_path", "second_path") |
| 14 |
exclude_opt_key = "exclude_from_my_middleware" |
| 15 |
|
| 16 |
async def handle(self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) -> None: |
| 17 |
start_time = time.monotonic() |
| 18 |
|
| 19 |
async def send_wrapper(message: "Message") -> None: |
| 20 |
if message["type"] == "http.response.start": |
| 21 |
process_time = time.monotonic() - start_time |
| 22 |
headers = MutableScopeHeaders.from_message(message=message) |
| 23 |
headers["X-Process-Time"] = str(process_time) |
| 24 |
await send(message) |
| 25 |
|
| 26 |
await next_app(scope, receive, send_wrapper) |
| 27 |
|
| 28 |
|
| 29 |
@websocket("/my-websocket") |
| 30 |
async def websocket_handler(socket: WebSocket) -> None: |
| 31 |
""" |
| 32 |
Websocket handler - is excluded because the middleware scopes includes 'ScopeType.HTTP' |
| 33 |
""" |
| 34 |
await socket.accept() |
| 35 |
await socket.send_json({"hello": "websocket"}) |
| 36 |
await socket.close() |
| 37 |
|
| 38 |
|
| 39 |
@get("/first_path", sync_to_thread=False) |
| 40 |
def first_handler() -> Dict[str, str]: |
| 41 |
"""Handler is excluded due to regex pattern matching "first_path".""" |
| 42 |
return {"hello": "first"} |
| 43 |
|
| 44 |
|
| 45 |
@get("/second_path", sync_to_thread=False) |
| 46 |
def second_handler() -> Dict[str, str]: |
| 47 |
"""Handler is excluded due to regex pattern matching "second_path".""" |
| 48 |
return {"hello": "second"} |
| 49 |
|
| 50 |
|
| 51 |
@get("/third_path", exclude_from_my_middleware=True, sync_to_thread=False) |
| 52 |
def third_handler() -> Dict[str, str]: |
| 53 |
"""Handler is excluded due to the opt key 'exclude_from_my_middleware' matching the middleware 'exclude_opt_key'.""" |
| 54 |
return {"hello": "third"} |
| 55 |
|
| 56 |
|
| 57 |
@get("/greet", sync_to_thread=False) |
| 58 |
def not_excluded_handler() -> Dict[str, str]: |
| 59 |
"""This handler is not excluded, and thus the middleware will execute on every incoming request to it.""" |
| 60 |
return {"hello": "world"} |
| 61 |
|
| 62 |
|
| 63 |
app = Litestar( |
| 64 |
route_handlers=[ |
| 65 |
websocket_handler, |
| 66 |
first_handler, |
| 67 |
second_handler, |
| 68 |
third_handler, |
| 69 |
not_excluded_handler, |
| 70 |
], |
| 71 |
middleware=[MyMiddleware()], |
| 72 |
) |