add State object to Application and Request

This commit is contained in:
Izalia Mae 2024-04-12 05:52:14 -04:00
parent 97e9668865
commit 6ffe05c977
3 changed files with 24 additions and 3 deletions

View file

@ -6,6 +6,7 @@ from pathlib import Path
from typing import Any, TypeVar
from .error import HttpError
from .misc import State
from .objtypes import ScopeType
from .request import Request
from .response import Response, TemplateResponse
@ -42,6 +43,7 @@ class Application:
self.env: dict[str, str] = env or {}
self.dev: bool = dev
self.reload_dirs: list[Path | str] = reload_dirs or []
self.state: State = State()
# Not sure how to properly annotate `Exception` here, so just ignore the warnings
self.error_handlers: dict[type[ExceptionType], ExceptionCallback] = { # type: ignore

View file

@ -318,3 +318,20 @@ class Color(str):
values = ", ".join(str(value) for value in self.rgb)
trans = opacity / 100
return f"rgba({values}, {trans:.2})"
class State(dict[str, Any]):
def __getattr__(self, key: str) -> Any:
try:
object.__getattribute__(self, key)
except AttributeError:
return self[key]
def __setattr__(self, key: str, value: Any) -> None:
self[key] = value
def __delattr__(self, key: str) -> None:
del self[key]

View file

@ -7,6 +7,8 @@ from multidict import CIMultiDict, CIMultiDictProxy
from typing import Any, Literal, TypedDict
from urllib.parse import parse_qsl
from .misc import State
if typing.TYPE_CHECKING:
from .application import Application
@ -44,10 +46,10 @@ class Request:
self.path: str = scope["path"]
self.query: CIMultiDictProxy[str] = CIMultiDictProxy(CIMultiDict(raw_query))
self.headers: CIMultiDictProxy[str] = CIMultiDictProxy(CIMultiDict(raw_headers))
self.remote: str = scope.get("client", ("n/a", None))[0] # type: ignore[index]
self.local: str = scope.get("server", ("n/a", None))[0] # type: ignore[index]
self.remote: str = (scope.get("client") or ("n/a"))[0]
self.local: str = (scope.get("server") or ("n/a"))[0]
self.state: dict[str, Any] = scope.get("state", {}) # type: ignore[assignment]
self.state: State = State(scope.get("state") or {})
self.extensions: dict[str, Any] = scope.get("extensions", {}) # type: ignore[assignment]
# keep?