| 1 |
import anyio |
| 2 |
|
| 3 |
from litestar import Litestar, get |
| 4 |
from litestar.enums import ScopeType |
| 5 |
from litestar.exceptions import ClientException |
| 6 |
from litestar.middleware import ASGIMiddleware |
| 7 |
from litestar.types import ASGIApp, Receive, Scope, Send |
| 8 |
|
| 9 |
|
| 10 |
class TimeoutMiddleware(ASGIMiddleware): |
| 11 |
# we can configure some things on the class level here, related to when our |
| 12 |
# middleware should be applied. |
| 13 |
|
| 14 |
# if the requests' 'scope["type"]' is not "http", the middleware will be skipped |
| 15 |
scopes = (ScopeType.HTTP,) |
| 16 |
|
| 17 |
# if the handler for a request has set an opt of 'no_timeout=True', the middleware |
| 18 |
# will be skipped |
| 19 |
exclude_opt_key = "no_timeout" |
| 20 |
|
| 21 |
# the base class does not define an '__init__' method, so we're free to overwrite |
| 22 |
# this, which we're making use of to add some configuration |
| 23 |
def __init__( |
| 24 |
self, |
| 25 |
timeout: float, |
| 26 |
exclude_path_pattern: str | tuple[str, ...] | None = None, |
| 27 |
) -> None: |
| 28 |
self.timeout = timeout |
| 29 |
|
| 30 |
# we can also dynamically configure the options provided by the base class on |
| 31 |
# the instance level |
| 32 |
self.exclude_path_pattern = exclude_path_pattern |
| 33 |
|
| 34 |
async def handle(self, scope: Scope, receive: Receive, send: Send, next_app: ASGIApp) -> None: |
| 35 |
try: |
| 36 |
with anyio.fail_after(self.timeout): |
| 37 |
# call the next app in the chain |
| 38 |
await next_app(scope, receive, send) |
| 39 |
except TimeoutError: |
| 40 |
# if the request has timed out, raise an exception. since the whole |
| 41 |
# application is wrapped in an exception handling middleware, it will |
| 42 |
# transform this exception into a response for us |
| 43 |
raise ClientException(status_code=408) from None |
| 44 |
|
| 45 |
|
| 46 |
@get("/", no_timeout=True) |
| 47 |
async def handler_with_opt_skip() -> None: |
| 48 |
pass |
| 49 |
|
| 50 |
|
| 51 |
@get("/not-this-path") |
| 52 |
async def handler_with_path_skip() -> None: |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
app = Litestar( |
| 57 |
route_handlers=[ |
| 58 |
handler_with_opt_skip, |
| 59 |
handler_with_path_skip, |
| 60 |
], |
| 61 |
middleware=[TimeoutMiddleware(timeout=5)], |
| 62 |
) |