Depot
Depot is used to store temporary data involved in a single request. Middleware can place the temporary data it processes into the Depot for use by subsequent programs.
When a server receives a request from a client browser, it creates an instance of Depot. This instance is destroyed after all middleware and Handler have finished processing the request.
For example, we can set current_user in a login middleware and then read the current user information in subsequent middleware or Handler.
Quick Understanding
Depot is used to store and share data during request processing. It implements a type-safe data container that supports two main usage patterns:
- Key-Value Storage: Access values associated with string keys via
insert/getmethods. - Type Injection: Store and retrieve values based on type via
inject/obtainmethods.
As shown in the examples, Depot is particularly useful for passing data between middleware and handlers. Middleware can set values in Depot (such as user information, authentication status), and subsequent handlers can retrieve these values without redundant calculations or queries. The design of Depot ensures data consistency and accessibility throughout the entire request processing chain, making it a core tool for building complex web applications.
Setting and Retrieving Data via insert and get
As shown above, you can insert key and value into Depot using insert. For values of this type, you can directly retrieve them using get.
If the key does not exist, or if the key exists but the type does not match, it returns None.
Setting and Retrieving Data via inject and obtain
Sometimes, there are scenarios where a unique instance exists for a type without needing to relate to a specific key. You can use inject to insert data and then use obtain to retrieve it. These methods do not require you to provide a key.