Get the state for a token. Args: token: The token to get the state for. Returns: The state for the token.
(
self,
token: StateToken[TOKEN_TYPE],
)
| 157 | |
| 158 | @override |
| 159 | async def get_state( |
| 160 | self, |
| 161 | token: StateToken[TOKEN_TYPE], |
| 162 | ) -> TOKEN_TYPE: |
| 163 | """Get the state for a token. |
| 164 | |
| 165 | Args: |
| 166 | token: The token to get the state for. |
| 167 | |
| 168 | Returns: |
| 169 | The state for the token. |
| 170 | """ |
| 171 | token = self._coerce_token(token) |
| 172 | root_state = self.states.get(token.cache_key) |
| 173 | self._token_last_touched[token.cache_key] = time.time() |
| 174 | if root_state is not None: |
| 175 | # Retrieved state from memory. |
| 176 | return root_state |
| 177 | |
| 178 | # Deserialize root state from disk. |
| 179 | if isinstance(token, BaseStateToken): |
| 180 | # Find the root state |
| 181 | root_state_cls = token.cls.get_root_state() |
| 182 | root_state = await self.load_state(token.with_cls(root_state_cls)) |
| 183 | # Create a new root state tree with all substates instantiated. |
| 184 | fresh_root_state = root_state_cls(_reflex_internal_init=True) |
| 185 | if root_state is None: |
| 186 | root_state = fresh_root_state |
| 187 | elif not isinstance(root_state, BaseState): |
| 188 | msg = "Deserialized state is not an instance of BaseState, cannot populate substates." |
| 189 | raise TypeError(msg) |
| 190 | else: |
| 191 | # Ensure all substates exist, even if they were not serialized previously. |
| 192 | root_state.substates = fresh_root_state.substates |
| 193 | await self.populate_substates(token, root_state, root_state) |
| 194 | self.states[token.cache_key] = root_state |
| 195 | return cast(TOKEN_TYPE, root_state) |
| 196 | # For non-BaseState tokens, if the deserialized state is None, we create a new instance using the token's cls. |
| 197 | state = await self.load_state(token) |
| 198 | if state is None: |
| 199 | state = token.cls() |
| 200 | self.states[token.cache_key] = state |
| 201 | return cast(TOKEN_TYPE, state) |
| 202 | |
| 203 | async def set_state_for_substate( |
| 204 | self, token: StateToken[TOKEN_TYPE], substate: TOKEN_TYPE |