We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
StaticFilesConfig and virtual directories
I'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. 

This is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.

https://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlite/handlers/base.py`
Content:
```
1 from __future__ import annotations
2 
3 from copy import copy
4 from inspect import Signature
5 from typing import TYPE_CHECKING, Any, Generic, Mapping, Sequence, TypeVar, cast
6 
7 from starlite._signature.field import SignatureField
8 from starlite.exceptions import ImproperlyConfiguredException
9 from starlite.types import Dependencies, Empty, EmptyType, ExceptionHandlersMap, Guard, Middleware, TypeEncodersMap
10 from starlite.utils import AsyncCallable, Ref, get_name, normalize_path
11 from starlite.utils.helpers import unwrap_partial
12 
13 __all__ = ("BaseRouteHandler",)
14 
15 
16 if TYPE_CHECKING:
17     from typing_extensions import Self
18 
19     from starlite._signature.models import SignatureModel
20     from starlite.connection import ASGIConnection
21     from starlite.controller import Controller
22     from starlite.di import Provide
23     from starlite.params import ParameterKwarg
24     from starlite.router import Router
25     from starlite.types import AnyCallable, AsyncAnyCallable, ExceptionHandler
26     from starlite.types.composite_types import MaybePartial
27 
28 T = TypeVar("T", bound="BaseRouteHandler")
29 
30 
31 class BaseRouteHandler(Generic[T]):
32     """Base route handler.
33 
34     Serves as a subclass for all route handlers
35     """
36 
37     fn: Ref[MaybePartial[AnyCallable]]
38     signature: Signature
39 
40     __slots__ = (
41         "_resolved_dependencies",
42         "_resolved_guards",
43         "_resolved_layered_parameters",
44         "_resolved_signature_namespace",
45         "_resolved_type_encoders",
46         "dependencies",
47         "exception_handlers",
48         "fn",
49         "guards",
50         "middleware",
51         "name",
52         "opt",
53         "owner",
54         "paths",
55         "signature",
56         "signature_model",
57         "signature_namespace",
58         "type_encoders",
59     )
60 
61     def __init__(
62         self,
63         path: str | Sequence[str] | None = None,
64         *,
65         dependencies: Dependencies | None = None,
66         exception_handlers: ExceptionHandlersMap | None = None,
67         guards: Sequence[Guard] | None = None,
68         middleware: Sequence[Middleware] | None = None,
69         name: str | None = None,
70         opt: Mapping[str, Any] | None = None,
71         signature_namespace: Mapping[str, Any] | None = None,
72         type_encoders: TypeEncodersMap | None = None,
73         **kwargs: Any,
74     ) -> None:
75         """Initialize ``HTTPRouteHandler``.
76 
77         Args:
78             path: A path fragment for the route handler function or a sequence of path fragments. If not given defaults
79                 to ``/``
80             dependencies: A string keyed mapping of dependency :class:`Provider <.di.Provide>` instances.
81             exception_handlers: A mapping of status codes and/or exception types to handler functions.
82             guards: A sequence of :class:`Guard <.types.Guard>` callables.
83             middleware: A sequence of :class:`Middleware <.types.Middleware>`.
84             name: A string identifying the route handler.
85             opt: A string keyed mapping of arbitrary values that can be accessed in :class:`Guards <.types.Guard>` or
86                 wherever you have access to :class:`Request <.connection.Request>` or
87                 :class:`ASGI Scope <.types.Scope>`.
88             signature_namespace: A mapping of names to types for use in forward reference resolution during signature modelling.
89             type_encoders: A mapping of types to callables that transform them into types supported for serialization.
90             **kwargs: Any additional kwarg - will be set in the opt dictionary.
91         """
92         self._resolved_dependencies: dict[str, Provide] | EmptyType = Empty
93         self._resolved_guards: list[Guard] | EmptyType = Empty
94         self._resolved_layered_parameters: dict[str, SignatureField] | EmptyType = Empty
95         self._resolved_signature_namespace: dict[str, Any] | EmptyType = Empty
96         self._resolved_type_encoders: TypeEncodersMap | EmptyType = Empty
97 
98         self.dependencies = dependencies
99         self.exception_handlers = exception_handlers
100         self.guards = guards
101         self.middleware = middleware
102         self.name = name
103         self.opt = dict(opt or {})
104         self.owner: Controller | Router | None = None
105         self.signature_model: type[SignatureModel] | None = None
106         self.signature_namespace = signature_namespace or {}
107         self.paths = (
108             {normalize_path(p) for p in path}
109             if path and isinstance(path, list)
110             else {normalize_path(path or "/")}  # type: ignore
111         )
112         self.opt.update(**kwargs)
113         self.type_encoders = type_encoders
114 
115     def __call__(self, fn: AsyncAnyCallable) -> Self:
116         """Replace a function with itself."""
117         self.fn = Ref["MaybePartial[AsyncAnyCallable]"](fn)
118         self.signature = Signature.from_callable(fn)
119         self._validate_handler_function()
120         return self
121 
122     @property
123     def handler_name(self) -> str:
124         """Get the name of the handler function.
125 
126         Raises:
127             ImproperlyConfiguredException: if handler fn is not set.
128 
129         Returns:
130             Name of the handler function
131         """
132         fn = getattr(self, "fn", None)
133         if not fn:
134             raise ImproperlyConfiguredException("cannot access handler name before setting the handler function")
135         return get_name(unwrap_partial(self.fn.value))
136 
137     @property
138     def dependency_name_set(self) -> set[str]:
139         """Set of all dependency names provided in the handler's ownership layers."""
140         layered_dependencies = (layer.dependencies or {} for layer in self.ownership_layers)
141         return {name for layer in layered_dependencies for name in layer}
142 
143     @property
144     def ownership_layers(self) -> list[T | Controller | Router]:
145         """Return the handler layers from the app down to the route handler.
146 
147         ``app -> ... -> route handler``
148         """
149         layers = []
150 
151         cur: Any = self
152         while cur:
153             layers.append(cur)
154             cur = cur.owner
155 
156         return list(reversed(layers))
157 
158     def resolve_type_encoders(self) -> TypeEncodersMap:
159         """Return a merged type_encoders mapping.
160 
161         This method is memoized so the computation occurs only once.
162 
163         Returns:
164             A dict of type encoders
165         """
166         if self._resolved_type_encoders is Empty:
167             self._resolved_type_encoders = {}
168 
169             for layer in self.ownership_layers:
170                 if type_encoders := getattr(layer, "type_encoders", None):
171                     self._resolved_type_encoders.update(type_encoders)
172         return cast("TypeEncodersMap", self._resolved_type_encoders)
173 
174     def resolve_layered_parameters(self) -> dict[str, SignatureField]:
175         """Return all parameters declared above the handler."""
176         if self._resolved_layered_parameters is Empty:
177             parameter_kwargs: dict[str, ParameterKwarg] = {}
178 
179             for layer in self.ownership_layers:
180                 parameter_kwargs.update(getattr(layer, "parameters", {}) or {})
181 
182             self._resolved_layered_parameters = {
183                 key: SignatureField.create(
184                     name=key, field_type=parameter.value_type, default_value=parameter.default, kwarg_model=parameter
185                 )
186                 for key, parameter in parameter_kwargs.items()
187             }
188 
189         return cast("dict[str, SignatureField]", self._resolved_layered_parameters)
190 
191     def resolve_guards(self) -> list[Guard]:
192         """Return all guards in the handlers scope, starting from highest to current layer."""
193         if self._resolved_guards is Empty:
194             self._resolved_guards = []
195 
196             for layer in self.ownership_layers:
197                 self._resolved_guards.extend(layer.guards or [])
198 
199             self._resolved_guards = cast("list[Guard]", [AsyncCallable(guard) for guard in self._resolved_guards])
200 
201         return self._resolved_guards  # type:ignore
202 
203     def resolve_dependencies(self) -> dict[str, Provide]:
204         """Return all dependencies correlating to handler function's kwargs that exist in the handler's scope."""
205         if self._resolved_dependencies is Empty:
206             self._resolved_dependencies = {}
207 
208             for layer in self.ownership_layers:
209                 for key, value in (layer.dependencies or {}).items():
210                     self._validate_dependency_is_unique(
211                         dependencies=self._resolved_dependencies, key=key, provider=value
212                     )
213                     self._resolved_dependencies[key] = value
214 
215         return cast("dict[str, Provide]", self._resolved_dependencies)
216 
217     def resolve_middleware(self) -> list[Middleware]:
218         """Build the middleware stack for the RouteHandler and return it.
219 
220         The middlewares are added from top to bottom (``app -> router -> controller -> route handler``) and then
221         reversed.
222         """
223         resolved_middleware: list[Middleware] = []
224         for layer in self.ownership_layers:
225             resolved_middleware.extend(layer.middleware or [])
226         return list(reversed(resolved_middleware))
227 
228     def resolve_exception_handlers(self) -> ExceptionHandlersMap:
229         """Resolve the exception_handlers by starting from the route handler and moving up.
230 
231         This method is memoized so the computation occurs only once.
232         """
233         resolved_exception_handlers: dict[int | type[Exception], ExceptionHandler] = {}
234         for layer in self.ownership_layers:
235             resolved_exception_handlers.update(layer.exception_handlers or {})
236         return resolved_exception_handlers
237 
238     def resolve_opts(self) -> None:
239         """Build the route handler opt dictionary by going from top to bottom.
240 
241         When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the
242         layer closest to the response handler will take precedence.
243         """
244 
245         opt: dict[str, Any] = {}
246         for layer in self.ownership_layers:
247             opt.update(layer.opt or {})
248 
249         self.opt = opt
250 
251     def resolve_signature_namespace(self) -> dict[str, Any]:
252         """Build the route handler signature namespace dictionary by going from top to bottom.
253 
254         When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the
255         layer closest to the response handler will take precedence.
256         """
257         if self._resolved_layered_parameters is Empty:
258             ns: dict[str, Any] = {}
259             for layer in self.ownership_layers:
260                 ns.update(layer.signature_namespace)
261 
262             self._resolved_signature_namespace = ns
263         return cast("dict[str, Any]", self._resolved_signature_namespace)
264 
265     async def authorize_connection(self, connection: "ASGIConnection") -> None:
266         """Ensure the connection is authorized by running all the route guards in scope."""
267         for guard in self.resolve_guards():
268             await guard(connection, copy(self))  # type: ignore
269 
270     @staticmethod
271     def _validate_dependency_is_unique(dependencies: dict[str, Provide], key: str, provider: Provide) -> None:
272         """Validate that a given provider has not been already defined under a different key."""
273         for dependency_key, value in dependencies.items():
274             if provider == value:
275                 raise ImproperlyConfiguredException(
276                     f"Provider for key {key} is already defined under the different key {dependency_key}. "
277                     f"If you wish to override a provider, it must have the same key."
278                 )
279 
280     def _validate_handler_function(self) -> None:
281         """Validate the route handler function once set by inspecting its return annotations."""
282         if not getattr(self, "fn", None):
283             raise ImproperlyConfiguredException("Cannot call _validate_handler_function without first setting self.fn")
284 
285     def __str__(self) -> str:
286         """Return a unique identifier for the route handler.
287 
288         Returns:
289             A string
290         """
291         target = unwrap_partial(self.fn.value)
292         if not hasattr(target, "__qualname__"):
293             target = type(target)
294         return f"{target.__module__}.{target.__qualname__}"
295
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/starlite/handlers/base.py b/starlite/handlers/base.py
--- a/starlite/handlers/base.py
+++ b/starlite/handlers/base.py
@@ -22,7 +22,7 @@
     from starlite.di import Provide
     from starlite.params import ParameterKwarg
     from starlite.router import Router
-    from starlite.types import AnyCallable, AsyncAnyCallable, ExceptionHandler
+    from starlite.types import AsyncAnyCallable, ExceptionHandler
     from starlite.types.composite_types import MaybePartial
 
 T = TypeVar("T", bound="BaseRouteHandler")
@@ -34,10 +34,10 @@
     Serves as a subclass for all route handlers
     """
 
-    fn: Ref[MaybePartial[AnyCallable]]
     signature: Signature
 
     __slots__ = (
+        "_fn",
         "_resolved_dependencies",
         "_resolved_guards",
         "_resolved_layered_parameters",
@@ -45,7 +45,6 @@
         "_resolved_type_encoders",
         "dependencies",
         "exception_handlers",
-        "fn",
         "guards",
         "middleware",
         "name",
@@ -114,11 +113,25 @@
 
     def __call__(self, fn: AsyncAnyCallable) -> Self:
         """Replace a function with itself."""
-        self.fn = Ref["MaybePartial[AsyncAnyCallable]"](fn)
+        self._fn = Ref["MaybePartial[AsyncAnyCallable]"](fn)
         self.signature = Signature.from_callable(fn)
         self._validate_handler_function()
         return self
 
+    @property
+    def fn(self) -> Ref[MaybePartial[AsyncAnyCallable]]:
+        """Get the handler function.
+
+        Raises:
+            ImproperlyConfiguredException: if handler fn is not set.
+
+        Returns:
+            Handler function
+        """
+        if not hasattr(self, "_fn"):
+            raise ImproperlyConfiguredException("Handler has not decorated a function")
+        return self._fn
+
     @property
     def handler_name(self) -> str:
         """Get the name of the handler function.
@@ -129,9 +142,6 @@
         Returns:
             Name of the handler function
         """
-        fn = getattr(self, "fn", None)
-        if not fn:
-            raise ImproperlyConfiguredException("cannot access handler name before setting the handler function")
         return get_name(unwrap_partial(self.fn.value))
 
     @property
@@ -279,8 +289,6 @@
 
     def _validate_handler_function(self) -> None:
         """Validate the route handler function once set by inspecting its return annotations."""
-        if not getattr(self, "fn", None):
-            raise ImproperlyConfiguredException("Cannot call _validate_handler_function without first setting self.fn")
 
     def __str__(self) -> str:
         """Return a unique identifier for the route handler.
@@ -288,6 +296,7 @@
         Returns:
             A string
         """
+        target: type[AsyncAnyCallable] | AsyncAnyCallable
         target = unwrap_partial(self.fn.value)
         if not hasattr(target, "__qualname__"):
             target = type(target)

{"golden_diff": "diff --git a/starlite/handlers/base.py b/starlite/handlers/base.py\n--- a/starlite/handlers/base.py\n+++ b/starlite/handlers/base.py\n@@ -22,7 +22,7 @@\n     from starlite.di import Provide\n     from starlite.params import ParameterKwarg\n     from starlite.router import Router\n-    from starlite.types import AnyCallable, AsyncAnyCallable, ExceptionHandler\n+    from starlite.types import AsyncAnyCallable, ExceptionHandler\n     from starlite.types.composite_types import MaybePartial\n \n T = TypeVar(\"T\", bound=\"BaseRouteHandler\")\n@@ -34,10 +34,10 @@\n     Serves as a subclass for all route handlers\n     \"\"\"\n \n-    fn: Ref[MaybePartial[AnyCallable]]\n     signature: Signature\n \n     __slots__ = (\n+        \"_fn\",\n         \"_resolved_dependencies\",\n         \"_resolved_guards\",\n         \"_resolved_layered_parameters\",\n@@ -45,7 +45,6 @@\n         \"_resolved_type_encoders\",\n         \"dependencies\",\n         \"exception_handlers\",\n-        \"fn\",\n         \"guards\",\n         \"middleware\",\n         \"name\",\n@@ -114,11 +113,25 @@\n \n     def __call__(self, fn: AsyncAnyCallable) -> Self:\n         \"\"\"Replace a function with itself.\"\"\"\n-        self.fn = Ref[\"MaybePartial[AsyncAnyCallable]\"](fn)\n+        self._fn = Ref[\"MaybePartial[AsyncAnyCallable]\"](fn)\n         self.signature = Signature.from_callable(fn)\n         self._validate_handler_function()\n         return self\n \n+    @property\n+    def fn(self) -> Ref[MaybePartial[AsyncAnyCallable]]:\n+        \"\"\"Get the handler function.\n+\n+        Raises:\n+            ImproperlyConfiguredException: if handler fn is not set.\n+\n+        Returns:\n+            Handler function\n+        \"\"\"\n+        if not hasattr(self, \"_fn\"):\n+            raise ImproperlyConfiguredException(\"Handler has not decorated a function\")\n+        return self._fn\n+\n     @property\n     def handler_name(self) -> str:\n         \"\"\"Get the name of the handler function.\n@@ -129,9 +142,6 @@\n         Returns:\n             Name of the handler function\n         \"\"\"\n-        fn = getattr(self, \"fn\", None)\n-        if not fn:\n-            raise ImproperlyConfiguredException(\"cannot access handler name before setting the handler function\")\n         return get_name(unwrap_partial(self.fn.value))\n \n     @property\n@@ -279,8 +289,6 @@\n \n     def _validate_handler_function(self) -> None:\n         \"\"\"Validate the route handler function once set by inspecting its return annotations.\"\"\"\n-        if not getattr(self, \"fn\", None):\n-            raise ImproperlyConfiguredException(\"Cannot call _validate_handler_function without first setting self.fn\")\n \n     def __str__(self) -> str:\n         \"\"\"Return a unique identifier for the route handler.\n@@ -288,6 +296,7 @@\n         Returns:\n             A string\n         \"\"\"\n+        target: type[AsyncAnyCallable] | AsyncAnyCallable\n         target = unwrap_partial(self.fn.value)\n         if not hasattr(target, \"__qualname__\"):\n             target = type(target)\n", "issue": "StaticFilesConfig and virtual directories\nI'm trying to write a ``FileSystemProtocol`` to load files from the package data using [importlib_resources](https://importlib-resources.readthedocs.io/en/latest/using.html#). But because ``directories`` is defined as ``DirectoryPath``, pydantic checks if the given directories exist in the local filesystem. \r\n\r\nThis is not generally true, especially in any kind of virtual filesystem (e.g. a zipped package). I think this condition should be relaxed to support virtual filesystems.\r\n\r\nhttps://github.com/starlite-api/starlite/blob/9bb6dcd57c10a591377cf8e3a537e9292566d5b9/starlite/config/static_files.py#L32\n", "before_files": [{"content": "from __future__ import annotations\n\nfrom copy import copy\nfrom inspect import Signature\nfrom typing import TYPE_CHECKING, Any, Generic, Mapping, Sequence, TypeVar, cast\n\nfrom starlite._signature.field import SignatureField\nfrom starlite.exceptions import ImproperlyConfiguredException\nfrom starlite.types import Dependencies, Empty, EmptyType, ExceptionHandlersMap, Guard, Middleware, TypeEncodersMap\nfrom starlite.utils import AsyncCallable, Ref, get_name, normalize_path\nfrom starlite.utils.helpers import unwrap_partial\n\n__all__ = (\"BaseRouteHandler\",)\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n    from starlite._signature.models import SignatureModel\n    from starlite.connection import ASGIConnection\n    from starlite.controller import Controller\n    from starlite.di import Provide\n    from starlite.params import ParameterKwarg\n    from starlite.router import Router\n    from starlite.types import AnyCallable, AsyncAnyCallable, ExceptionHandler\n    from starlite.types.composite_types import MaybePartial\n\nT = TypeVar(\"T\", bound=\"BaseRouteHandler\")\n\n\nclass BaseRouteHandler(Generic[T]):\n    \"\"\"Base route handler.\n\n    Serves as a subclass for all route handlers\n    \"\"\"\n\n    fn: Ref[MaybePartial[AnyCallable]]\n    signature: Signature\n\n    __slots__ = (\n        \"_resolved_dependencies\",\n        \"_resolved_guards\",\n        \"_resolved_layered_parameters\",\n        \"_resolved_signature_namespace\",\n        \"_resolved_type_encoders\",\n        \"dependencies\",\n        \"exception_handlers\",\n        \"fn\",\n        \"guards\",\n        \"middleware\",\n        \"name\",\n        \"opt\",\n        \"owner\",\n        \"paths\",\n        \"signature\",\n        \"signature_model\",\n        \"signature_namespace\",\n        \"type_encoders\",\n    )\n\n    def __init__(\n        self,\n        path: str | Sequence[str] | None = None,\n        *,\n        dependencies: Dependencies | None = None,\n        exception_handlers: ExceptionHandlersMap | None = None,\n        guards: Sequence[Guard] | None = None,\n        middleware: Sequence[Middleware] | None = None,\n        name: str | None = None,\n        opt: Mapping[str, Any] | None = None,\n        signature_namespace: Mapping[str, Any] | None = None,\n        type_encoders: TypeEncodersMap | None = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize ``HTTPRouteHandler``.\n\n        Args:\n            path: A path fragment for the route handler function or a sequence of path fragments. If not given defaults\n                to ``/``\n            dependencies: A string keyed mapping of dependency :class:`Provider <.di.Provide>` instances.\n            exception_handlers: A mapping of status codes and/or exception types to handler functions.\n            guards: A sequence of :class:`Guard <.types.Guard>` callables.\n            middleware: A sequence of :class:`Middleware <.types.Middleware>`.\n            name: A string identifying the route handler.\n            opt: A string keyed mapping of arbitrary values that can be accessed in :class:`Guards <.types.Guard>` or\n                wherever you have access to :class:`Request <.connection.Request>` or\n                :class:`ASGI Scope <.types.Scope>`.\n            signature_namespace: A mapping of names to types for use in forward reference resolution during signature modelling.\n            type_encoders: A mapping of types to callables that transform them into types supported for serialization.\n            **kwargs: Any additional kwarg - will be set in the opt dictionary.\n        \"\"\"\n        self._resolved_dependencies: dict[str, Provide] | EmptyType = Empty\n        self._resolved_guards: list[Guard] | EmptyType = Empty\n        self._resolved_layered_parameters: dict[str, SignatureField] | EmptyType = Empty\n        self._resolved_signature_namespace: dict[str, Any] | EmptyType = Empty\n        self._resolved_type_encoders: TypeEncodersMap | EmptyType = Empty\n\n        self.dependencies = dependencies\n        self.exception_handlers = exception_handlers\n        self.guards = guards\n        self.middleware = middleware\n        self.name = name\n        self.opt = dict(opt or {})\n        self.owner: Controller | Router | None = None\n        self.signature_model: type[SignatureModel] | None = None\n        self.signature_namespace = signature_namespace or {}\n        self.paths = (\n            {normalize_path(p) for p in path}\n            if path and isinstance(path, list)\n            else {normalize_path(path or \"/\")}  # type: ignore\n        )\n        self.opt.update(**kwargs)\n        self.type_encoders = type_encoders\n\n    def __call__(self, fn: AsyncAnyCallable) -> Self:\n        \"\"\"Replace a function with itself.\"\"\"\n        self.fn = Ref[\"MaybePartial[AsyncAnyCallable]\"](fn)\n        self.signature = Signature.from_callable(fn)\n        self._validate_handler_function()\n        return self\n\n    @property\n    def handler_name(self) -> str:\n        \"\"\"Get the name of the handler function.\n\n        Raises:\n            ImproperlyConfiguredException: if handler fn is not set.\n\n        Returns:\n            Name of the handler function\n        \"\"\"\n        fn = getattr(self, \"fn\", None)\n        if not fn:\n            raise ImproperlyConfiguredException(\"cannot access handler name before setting the handler function\")\n        return get_name(unwrap_partial(self.fn.value))\n\n    @property\n    def dependency_name_set(self) -> set[str]:\n        \"\"\"Set of all dependency names provided in the handler's ownership layers.\"\"\"\n        layered_dependencies = (layer.dependencies or {} for layer in self.ownership_layers)\n        return {name for layer in layered_dependencies for name in layer}\n\n    @property\n    def ownership_layers(self) -> list[T | Controller | Router]:\n        \"\"\"Return the handler layers from the app down to the route handler.\n\n        ``app -> ... -> route handler``\n        \"\"\"\n        layers = []\n\n        cur: Any = self\n        while cur:\n            layers.append(cur)\n            cur = cur.owner\n\n        return list(reversed(layers))\n\n    def resolve_type_encoders(self) -> TypeEncodersMap:\n        \"\"\"Return a merged type_encoders mapping.\n\n        This method is memoized so the computation occurs only once.\n\n        Returns:\n            A dict of type encoders\n        \"\"\"\n        if self._resolved_type_encoders is Empty:\n            self._resolved_type_encoders = {}\n\n            for layer in self.ownership_layers:\n                if type_encoders := getattr(layer, \"type_encoders\", None):\n                    self._resolved_type_encoders.update(type_encoders)\n        return cast(\"TypeEncodersMap\", self._resolved_type_encoders)\n\n    def resolve_layered_parameters(self) -> dict[str, SignatureField]:\n        \"\"\"Return all parameters declared above the handler.\"\"\"\n        if self._resolved_layered_parameters is Empty:\n            parameter_kwargs: dict[str, ParameterKwarg] = {}\n\n            for layer in self.ownership_layers:\n                parameter_kwargs.update(getattr(layer, \"parameters\", {}) or {})\n\n            self._resolved_layered_parameters = {\n                key: SignatureField.create(\n                    name=key, field_type=parameter.value_type, default_value=parameter.default, kwarg_model=parameter\n                )\n                for key, parameter in parameter_kwargs.items()\n            }\n\n        return cast(\"dict[str, SignatureField]\", self._resolved_layered_parameters)\n\n    def resolve_guards(self) -> list[Guard]:\n        \"\"\"Return all guards in the handlers scope, starting from highest to current layer.\"\"\"\n        if self._resolved_guards is Empty:\n            self._resolved_guards = []\n\n            for layer in self.ownership_layers:\n                self._resolved_guards.extend(layer.guards or [])\n\n            self._resolved_guards = cast(\"list[Guard]\", [AsyncCallable(guard) for guard in self._resolved_guards])\n\n        return self._resolved_guards  # type:ignore\n\n    def resolve_dependencies(self) -> dict[str, Provide]:\n        \"\"\"Return all dependencies correlating to handler function's kwargs that exist in the handler's scope.\"\"\"\n        if self._resolved_dependencies is Empty:\n            self._resolved_dependencies = {}\n\n            for layer in self.ownership_layers:\n                for key, value in (layer.dependencies or {}).items():\n                    self._validate_dependency_is_unique(\n                        dependencies=self._resolved_dependencies, key=key, provider=value\n                    )\n                    self._resolved_dependencies[key] = value\n\n        return cast(\"dict[str, Provide]\", self._resolved_dependencies)\n\n    def resolve_middleware(self) -> list[Middleware]:\n        \"\"\"Build the middleware stack for the RouteHandler and return it.\n\n        The middlewares are added from top to bottom (``app -> router -> controller -> route handler``) and then\n        reversed.\n        \"\"\"\n        resolved_middleware: list[Middleware] = []\n        for layer in self.ownership_layers:\n            resolved_middleware.extend(layer.middleware or [])\n        return list(reversed(resolved_middleware))\n\n    def resolve_exception_handlers(self) -> ExceptionHandlersMap:\n        \"\"\"Resolve the exception_handlers by starting from the route handler and moving up.\n\n        This method is memoized so the computation occurs only once.\n        \"\"\"\n        resolved_exception_handlers: dict[int | type[Exception], ExceptionHandler] = {}\n        for layer in self.ownership_layers:\n            resolved_exception_handlers.update(layer.exception_handlers or {})\n        return resolved_exception_handlers\n\n    def resolve_opts(self) -> None:\n        \"\"\"Build the route handler opt dictionary by going from top to bottom.\n\n        When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the\n        layer closest to the response handler will take precedence.\n        \"\"\"\n\n        opt: dict[str, Any] = {}\n        for layer in self.ownership_layers:\n            opt.update(layer.opt or {})\n\n        self.opt = opt\n\n    def resolve_signature_namespace(self) -> dict[str, Any]:\n        \"\"\"Build the route handler signature namespace dictionary by going from top to bottom.\n\n        When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the\n        layer closest to the response handler will take precedence.\n        \"\"\"\n        if self._resolved_layered_parameters is Empty:\n            ns: dict[str, Any] = {}\n            for layer in self.ownership_layers:\n                ns.update(layer.signature_namespace)\n\n            self._resolved_signature_namespace = ns\n        return cast(\"dict[str, Any]\", self._resolved_signature_namespace)\n\n    async def authorize_connection(self, connection: \"ASGIConnection\") -> None:\n        \"\"\"Ensure the connection is authorized by running all the route guards in scope.\"\"\"\n        for guard in self.resolve_guards():\n            await guard(connection, copy(self))  # type: ignore\n\n    @staticmethod\n    def _validate_dependency_is_unique(dependencies: dict[str, Provide], key: str, provider: Provide) -> None:\n        \"\"\"Validate that a given provider has not been already defined under a different key.\"\"\"\n        for dependency_key, value in dependencies.items():\n            if provider == value:\n                raise ImproperlyConfiguredException(\n                    f\"Provider for key {key} is already defined under the different key {dependency_key}. \"\n                    f\"If you wish to override a provider, it must have the same key.\"\n                )\n\n    def _validate_handler_function(self) -> None:\n        \"\"\"Validate the route handler function once set by inspecting its return annotations.\"\"\"\n        if not getattr(self, \"fn\", None):\n            raise ImproperlyConfiguredException(\"Cannot call _validate_handler_function without first setting self.fn\")\n\n    def __str__(self) -> str:\n        \"\"\"Return a unique identifier for the route handler.\n\n        Returns:\n            A string\n        \"\"\"\n        target = unwrap_partial(self.fn.value)\n        if not hasattr(target, \"__qualname__\"):\n            target = type(target)\n        return f\"{target.__module__}.{target.__qualname__}\"\n", "path": "starlite/handlers/base.py"}], "after_files": [{"content": "from __future__ import annotations\n\nfrom copy import copy\nfrom inspect import Signature\nfrom typing import TYPE_CHECKING, Any, Generic, Mapping, Sequence, TypeVar, cast\n\nfrom starlite._signature.field import SignatureField\nfrom starlite.exceptions import ImproperlyConfiguredException\nfrom starlite.types import Dependencies, Empty, EmptyType, ExceptionHandlersMap, Guard, Middleware, TypeEncodersMap\nfrom starlite.utils import AsyncCallable, Ref, get_name, normalize_path\nfrom starlite.utils.helpers import unwrap_partial\n\n__all__ = (\"BaseRouteHandler\",)\n\n\nif TYPE_CHECKING:\n    from typing_extensions import Self\n\n    from starlite._signature.models import SignatureModel\n    from starlite.connection import ASGIConnection\n    from starlite.controller import Controller\n    from starlite.di import Provide\n    from starlite.params import ParameterKwarg\n    from starlite.router import Router\n    from starlite.types import AsyncAnyCallable, ExceptionHandler\n    from starlite.types.composite_types import MaybePartial\n\nT = TypeVar(\"T\", bound=\"BaseRouteHandler\")\n\n\nclass BaseRouteHandler(Generic[T]):\n    \"\"\"Base route handler.\n\n    Serves as a subclass for all route handlers\n    \"\"\"\n\n    signature: Signature\n\n    __slots__ = (\n        \"_fn\",\n        \"_resolved_dependencies\",\n        \"_resolved_guards\",\n        \"_resolved_layered_parameters\",\n        \"_resolved_signature_namespace\",\n        \"_resolved_type_encoders\",\n        \"dependencies\",\n        \"exception_handlers\",\n        \"guards\",\n        \"middleware\",\n        \"name\",\n        \"opt\",\n        \"owner\",\n        \"paths\",\n        \"signature\",\n        \"signature_model\",\n        \"signature_namespace\",\n        \"type_encoders\",\n    )\n\n    def __init__(\n        self,\n        path: str | Sequence[str] | None = None,\n        *,\n        dependencies: Dependencies | None = None,\n        exception_handlers: ExceptionHandlersMap | None = None,\n        guards: Sequence[Guard] | None = None,\n        middleware: Sequence[Middleware] | None = None,\n        name: str | None = None,\n        opt: Mapping[str, Any] | None = None,\n        signature_namespace: Mapping[str, Any] | None = None,\n        type_encoders: TypeEncodersMap | None = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"Initialize ``HTTPRouteHandler``.\n\n        Args:\n            path: A path fragment for the route handler function or a sequence of path fragments. If not given defaults\n                to ``/``\n            dependencies: A string keyed mapping of dependency :class:`Provider <.di.Provide>` instances.\n            exception_handlers: A mapping of status codes and/or exception types to handler functions.\n            guards: A sequence of :class:`Guard <.types.Guard>` callables.\n            middleware: A sequence of :class:`Middleware <.types.Middleware>`.\n            name: A string identifying the route handler.\n            opt: A string keyed mapping of arbitrary values that can be accessed in :class:`Guards <.types.Guard>` or\n                wherever you have access to :class:`Request <.connection.Request>` or\n                :class:`ASGI Scope <.types.Scope>`.\n            signature_namespace: A mapping of names to types for use in forward reference resolution during signature modelling.\n            type_encoders: A mapping of types to callables that transform them into types supported for serialization.\n            **kwargs: Any additional kwarg - will be set in the opt dictionary.\n        \"\"\"\n        self._resolved_dependencies: dict[str, Provide] | EmptyType = Empty\n        self._resolved_guards: list[Guard] | EmptyType = Empty\n        self._resolved_layered_parameters: dict[str, SignatureField] | EmptyType = Empty\n        self._resolved_signature_namespace: dict[str, Any] | EmptyType = Empty\n        self._resolved_type_encoders: TypeEncodersMap | EmptyType = Empty\n\n        self.dependencies = dependencies\n        self.exception_handlers = exception_handlers\n        self.guards = guards\n        self.middleware = middleware\n        self.name = name\n        self.opt = dict(opt or {})\n        self.owner: Controller | Router | None = None\n        self.signature_model: type[SignatureModel] | None = None\n        self.signature_namespace = signature_namespace or {}\n        self.paths = (\n            {normalize_path(p) for p in path}\n            if path and isinstance(path, list)\n            else {normalize_path(path or \"/\")}  # type: ignore\n        )\n        self.opt.update(**kwargs)\n        self.type_encoders = type_encoders\n\n    def __call__(self, fn: AsyncAnyCallable) -> Self:\n        \"\"\"Replace a function with itself.\"\"\"\n        self._fn = Ref[\"MaybePartial[AsyncAnyCallable]\"](fn)\n        self.signature = Signature.from_callable(fn)\n        self._validate_handler_function()\n        return self\n\n    @property\n    def fn(self) -> Ref[MaybePartial[AsyncAnyCallable]]:\n        \"\"\"Get the handler function.\n\n        Raises:\n            ImproperlyConfiguredException: if handler fn is not set.\n\n        Returns:\n            Handler function\n        \"\"\"\n        if not hasattr(self, \"_fn\"):\n            raise ImproperlyConfiguredException(\"Handler has not decorated a function\")\n        return self._fn\n\n    @property\n    def handler_name(self) -> str:\n        \"\"\"Get the name of the handler function.\n\n        Raises:\n            ImproperlyConfiguredException: if handler fn is not set.\n\n        Returns:\n            Name of the handler function\n        \"\"\"\n        return get_name(unwrap_partial(self.fn.value))\n\n    @property\n    def dependency_name_set(self) -> set[str]:\n        \"\"\"Set of all dependency names provided in the handler's ownership layers.\"\"\"\n        layered_dependencies = (layer.dependencies or {} for layer in self.ownership_layers)\n        return {name for layer in layered_dependencies for name in layer}\n\n    @property\n    def ownership_layers(self) -> list[T | Controller | Router]:\n        \"\"\"Return the handler layers from the app down to the route handler.\n\n        ``app -> ... -> route handler``\n        \"\"\"\n        layers = []\n\n        cur: Any = self\n        while cur:\n            layers.append(cur)\n            cur = cur.owner\n\n        return list(reversed(layers))\n\n    def resolve_type_encoders(self) -> TypeEncodersMap:\n        \"\"\"Return a merged type_encoders mapping.\n\n        This method is memoized so the computation occurs only once.\n\n        Returns:\n            A dict of type encoders\n        \"\"\"\n        if self._resolved_type_encoders is Empty:\n            self._resolved_type_encoders = {}\n\n            for layer in self.ownership_layers:\n                if type_encoders := getattr(layer, \"type_encoders\", None):\n                    self._resolved_type_encoders.update(type_encoders)\n        return cast(\"TypeEncodersMap\", self._resolved_type_encoders)\n\n    def resolve_layered_parameters(self) -> dict[str, SignatureField]:\n        \"\"\"Return all parameters declared above the handler.\"\"\"\n        if self._resolved_layered_parameters is Empty:\n            parameter_kwargs: dict[str, ParameterKwarg] = {}\n\n            for layer in self.ownership_layers:\n                parameter_kwargs.update(getattr(layer, \"parameters\", {}) or {})\n\n            self._resolved_layered_parameters = {\n                key: SignatureField.create(\n                    name=key, field_type=parameter.value_type, default_value=parameter.default, kwarg_model=parameter\n                )\n                for key, parameter in parameter_kwargs.items()\n            }\n\n        return cast(\"dict[str, SignatureField]\", self._resolved_layered_parameters)\n\n    def resolve_guards(self) -> list[Guard]:\n        \"\"\"Return all guards in the handlers scope, starting from highest to current layer.\"\"\"\n        if self._resolved_guards is Empty:\n            self._resolved_guards = []\n\n            for layer in self.ownership_layers:\n                self._resolved_guards.extend(layer.guards or [])\n\n            self._resolved_guards = cast(\"list[Guard]\", [AsyncCallable(guard) for guard in self._resolved_guards])\n\n        return self._resolved_guards  # type:ignore\n\n    def resolve_dependencies(self) -> dict[str, Provide]:\n        \"\"\"Return all dependencies correlating to handler function's kwargs that exist in the handler's scope.\"\"\"\n        if self._resolved_dependencies is Empty:\n            self._resolved_dependencies = {}\n\n            for layer in self.ownership_layers:\n                for key, value in (layer.dependencies or {}).items():\n                    self._validate_dependency_is_unique(\n                        dependencies=self._resolved_dependencies, key=key, provider=value\n                    )\n                    self._resolved_dependencies[key] = value\n\n        return cast(\"dict[str, Provide]\", self._resolved_dependencies)\n\n    def resolve_middleware(self) -> list[Middleware]:\n        \"\"\"Build the middleware stack for the RouteHandler and return it.\n\n        The middlewares are added from top to bottom (``app -> router -> controller -> route handler``) and then\n        reversed.\n        \"\"\"\n        resolved_middleware: list[Middleware] = []\n        for layer in self.ownership_layers:\n            resolved_middleware.extend(layer.middleware or [])\n        return list(reversed(resolved_middleware))\n\n    def resolve_exception_handlers(self) -> ExceptionHandlersMap:\n        \"\"\"Resolve the exception_handlers by starting from the route handler and moving up.\n\n        This method is memoized so the computation occurs only once.\n        \"\"\"\n        resolved_exception_handlers: dict[int | type[Exception], ExceptionHandler] = {}\n        for layer in self.ownership_layers:\n            resolved_exception_handlers.update(layer.exception_handlers or {})\n        return resolved_exception_handlers\n\n    def resolve_opts(self) -> None:\n        \"\"\"Build the route handler opt dictionary by going from top to bottom.\n\n        When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the\n        layer closest to the response handler will take precedence.\n        \"\"\"\n\n        opt: dict[str, Any] = {}\n        for layer in self.ownership_layers:\n            opt.update(layer.opt or {})\n\n        self.opt = opt\n\n    def resolve_signature_namespace(self) -> dict[str, Any]:\n        \"\"\"Build the route handler signature namespace dictionary by going from top to bottom.\n\n        When merging keys from multiple layers, if the same key is defined by multiple layers, the value from the\n        layer closest to the response handler will take precedence.\n        \"\"\"\n        if self._resolved_layered_parameters is Empty:\n            ns: dict[str, Any] = {}\n            for layer in self.ownership_layers:\n                ns.update(layer.signature_namespace)\n\n            self._resolved_signature_namespace = ns\n        return cast(\"dict[str, Any]\", self._resolved_signature_namespace)\n\n    async def authorize_connection(self, connection: \"ASGIConnection\") -> None:\n        \"\"\"Ensure the connection is authorized by running all the route guards in scope.\"\"\"\n        for guard in self.resolve_guards():\n            await guard(connection, copy(self))  # type: ignore\n\n    @staticmethod\n    def _validate_dependency_is_unique(dependencies: dict[str, Provide], key: str, provider: Provide) -> None:\n        \"\"\"Validate that a given provider has not been already defined under a different key.\"\"\"\n        for dependency_key, value in dependencies.items():\n            if provider == value:\n                raise ImproperlyConfiguredException(\n                    f\"Provider for key {key} is already defined under the different key {dependency_key}. \"\n                    f\"If you wish to override a provider, it must have the same key.\"\n                )\n\n    def _validate_handler_function(self) -> None:\n        \"\"\"Validate the route handler function once set by inspecting its return annotations.\"\"\"\n\n    def __str__(self) -> str:\n        \"\"\"Return a unique identifier for the route handler.\n\n        Returns:\n            A string\n        \"\"\"\n        target: type[AsyncAnyCallable] | AsyncAnyCallable\n        target = unwrap_partial(self.fn.value)\n        if not hasattr(target, \"__qualname__\"):\n            target = type(target)\n        return f\"{target.__module__}.{target.__qualname__}\"\n", "path": "starlite/handlers/base.py"}]}