reflex 0.8.14.post1__py3-none-any.whl → 0.8.15__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of reflex might be problematic. Click here for more details.
- reflex/.templates/web/utils/state.js +68 -8
- reflex/__init__.py +12 -7
- reflex/__init__.pyi +11 -3
- reflex/app.py +10 -7
- reflex/base.py +58 -33
- reflex/components/datadisplay/dataeditor.py +17 -2
- reflex/components/datadisplay/dataeditor.pyi +6 -2
- reflex/components/field.py +3 -1
- reflex/components/lucide/icon.py +2 -1
- reflex/components/lucide/icon.pyi +2 -1
- reflex/components/markdown/markdown.py +101 -27
- reflex/components/sonner/toast.py +3 -2
- reflex/components/sonner/toast.pyi +3 -2
- reflex/constants/base.py +5 -0
- reflex/constants/installer.py +3 -3
- reflex/environment.py +9 -1
- reflex/event.py +3 -0
- reflex/istate/manager/__init__.py +120 -0
- reflex/istate/manager/disk.py +210 -0
- reflex/istate/manager/memory.py +76 -0
- reflex/istate/{manager.py → manager/redis.py} +5 -372
- reflex/istate/proxy.py +35 -24
- reflex/model.py +534 -511
- reflex/plugins/tailwind_v4.py +2 -2
- reflex/reflex.py +16 -10
- reflex/state.py +35 -34
- reflex/testing.py +12 -14
- reflex/utils/build.py +11 -1
- reflex/utils/codespaces.py +30 -1
- reflex/utils/compat.py +51 -48
- reflex/utils/misc.py +2 -1
- reflex/utils/monitoring.py +1 -2
- reflex/utils/prerequisites.py +19 -4
- reflex/utils/processes.py +3 -1
- reflex/utils/redir.py +21 -37
- reflex/utils/serializers.py +21 -20
- reflex/utils/telemetry.py +0 -2
- reflex/utils/templates.py +4 -4
- reflex/utils/types.py +89 -90
- reflex/vars/base.py +108 -41
- reflex/vars/color.py +28 -8
- reflex/vars/datetime.py +6 -2
- reflex/vars/dep_tracking.py +2 -2
- reflex/vars/number.py +26 -0
- reflex/vars/object.py +51 -7
- reflex/vars/sequence.py +32 -1
- {reflex-0.8.14.post1.dist-info → reflex-0.8.15.dist-info}/METADATA +8 -3
- {reflex-0.8.14.post1.dist-info → reflex-0.8.15.dist-info}/RECORD +51 -48
- {reflex-0.8.14.post1.dist-info → reflex-0.8.15.dist-info}/WHEEL +0 -0
- {reflex-0.8.14.post1.dist-info → reflex-0.8.15.dist-info}/entry_points.txt +0 -0
- {reflex-0.8.14.post1.dist-info → reflex-0.8.15.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,387 +1,29 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""A state manager that stores states in redis."""
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import contextlib
|
|
5
5
|
import dataclasses
|
|
6
|
-
import functools
|
|
7
6
|
import time
|
|
8
7
|
import uuid
|
|
9
|
-
from abc import ABC, abstractmethod
|
|
10
8
|
from collections.abc import AsyncIterator
|
|
11
|
-
from hashlib import md5
|
|
12
|
-
from pathlib import Path
|
|
13
9
|
|
|
14
10
|
from redis import ResponseError
|
|
15
11
|
from redis.asyncio import Redis
|
|
16
12
|
from redis.asyncio.client import PubSub
|
|
17
13
|
from typing_extensions import override
|
|
18
14
|
|
|
19
|
-
from reflex import constants
|
|
20
15
|
from reflex.config import get_config
|
|
21
16
|
from reflex.environment import environment
|
|
17
|
+
from reflex.istate.manager import StateManager, _default_token_expiration
|
|
22
18
|
from reflex.state import BaseState, _split_substate_key, _substate_key
|
|
23
|
-
from reflex.utils import console
|
|
19
|
+
from reflex.utils import console
|
|
24
20
|
from reflex.utils.exceptions import (
|
|
25
21
|
InvalidLockWarningThresholdError,
|
|
26
|
-
InvalidStateManagerModeError,
|
|
27
22
|
LockExpiredError,
|
|
28
23
|
StateSchemaMismatchError,
|
|
29
24
|
)
|
|
30
25
|
|
|
31
26
|
|
|
32
|
-
@dataclasses.dataclass
|
|
33
|
-
class StateManager(ABC):
|
|
34
|
-
"""A class to manage many client states."""
|
|
35
|
-
|
|
36
|
-
# The state class to use.
|
|
37
|
-
state: type[BaseState]
|
|
38
|
-
|
|
39
|
-
@classmethod
|
|
40
|
-
def create(cls, state: type[BaseState]):
|
|
41
|
-
"""Create a new state manager.
|
|
42
|
-
|
|
43
|
-
Args:
|
|
44
|
-
state: The state class to use.
|
|
45
|
-
|
|
46
|
-
Raises:
|
|
47
|
-
InvalidStateManagerModeError: If the state manager mode is invalid.
|
|
48
|
-
|
|
49
|
-
Returns:
|
|
50
|
-
The state manager (either disk, memory or redis).
|
|
51
|
-
"""
|
|
52
|
-
config = get_config()
|
|
53
|
-
if prerequisites.parse_redis_url() is not None:
|
|
54
|
-
config.state_manager_mode = constants.StateManagerMode.REDIS
|
|
55
|
-
if config.state_manager_mode == constants.StateManagerMode.MEMORY:
|
|
56
|
-
return StateManagerMemory(state=state)
|
|
57
|
-
if config.state_manager_mode == constants.StateManagerMode.DISK:
|
|
58
|
-
return StateManagerDisk(state=state)
|
|
59
|
-
if config.state_manager_mode == constants.StateManagerMode.REDIS:
|
|
60
|
-
redis = prerequisites.get_redis()
|
|
61
|
-
if redis is not None:
|
|
62
|
-
# make sure expiration values are obtained only from the config object on creation
|
|
63
|
-
return StateManagerRedis(
|
|
64
|
-
state=state,
|
|
65
|
-
redis=redis,
|
|
66
|
-
token_expiration=config.redis_token_expiration,
|
|
67
|
-
lock_expiration=config.redis_lock_expiration,
|
|
68
|
-
lock_warning_threshold=config.redis_lock_warning_threshold,
|
|
69
|
-
)
|
|
70
|
-
msg = f"Expected one of: DISK, MEMORY, REDIS, got {config.state_manager_mode}"
|
|
71
|
-
raise InvalidStateManagerModeError(msg)
|
|
72
|
-
|
|
73
|
-
@abstractmethod
|
|
74
|
-
async def get_state(self, token: str) -> BaseState:
|
|
75
|
-
"""Get the state for a token.
|
|
76
|
-
|
|
77
|
-
Args:
|
|
78
|
-
token: The token to get the state for.
|
|
79
|
-
|
|
80
|
-
Returns:
|
|
81
|
-
The state for the token.
|
|
82
|
-
"""
|
|
83
|
-
|
|
84
|
-
@abstractmethod
|
|
85
|
-
async def set_state(self, token: str, state: BaseState):
|
|
86
|
-
"""Set the state for a token.
|
|
87
|
-
|
|
88
|
-
Args:
|
|
89
|
-
token: The token to set the state for.
|
|
90
|
-
state: The state to set.
|
|
91
|
-
"""
|
|
92
|
-
|
|
93
|
-
@abstractmethod
|
|
94
|
-
@contextlib.asynccontextmanager
|
|
95
|
-
async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
|
|
96
|
-
"""Modify the state for a token while holding exclusive lock.
|
|
97
|
-
|
|
98
|
-
Args:
|
|
99
|
-
token: The token to modify the state for.
|
|
100
|
-
|
|
101
|
-
Yields:
|
|
102
|
-
The state for the token.
|
|
103
|
-
"""
|
|
104
|
-
yield self.state()
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
@dataclasses.dataclass
|
|
108
|
-
class StateManagerMemory(StateManager):
|
|
109
|
-
"""A state manager that stores states in memory."""
|
|
110
|
-
|
|
111
|
-
# The mapping of client ids to states.
|
|
112
|
-
states: dict[str, BaseState] = dataclasses.field(default_factory=dict)
|
|
113
|
-
|
|
114
|
-
# The mutex ensures the dict of mutexes is updated exclusively
|
|
115
|
-
_state_manager_lock: asyncio.Lock = dataclasses.field(default=asyncio.Lock())
|
|
116
|
-
|
|
117
|
-
# The dict of mutexes for each client
|
|
118
|
-
_states_locks: dict[str, asyncio.Lock] = dataclasses.field(
|
|
119
|
-
default_factory=dict, init=False
|
|
120
|
-
)
|
|
121
|
-
|
|
122
|
-
@override
|
|
123
|
-
async def get_state(self, token: str) -> BaseState:
|
|
124
|
-
"""Get the state for a token.
|
|
125
|
-
|
|
126
|
-
Args:
|
|
127
|
-
token: The token to get the state for.
|
|
128
|
-
|
|
129
|
-
Returns:
|
|
130
|
-
The state for the token.
|
|
131
|
-
"""
|
|
132
|
-
# Memory state manager ignores the substate suffix and always returns the top-level state.
|
|
133
|
-
token = _split_substate_key(token)[0]
|
|
134
|
-
if token not in self.states:
|
|
135
|
-
self.states[token] = self.state(_reflex_internal_init=True)
|
|
136
|
-
return self.states[token]
|
|
137
|
-
|
|
138
|
-
@override
|
|
139
|
-
async def set_state(self, token: str, state: BaseState):
|
|
140
|
-
"""Set the state for a token.
|
|
141
|
-
|
|
142
|
-
Args:
|
|
143
|
-
token: The token to set the state for.
|
|
144
|
-
state: The state to set.
|
|
145
|
-
"""
|
|
146
|
-
token = _split_substate_key(token)[0]
|
|
147
|
-
self.states[token] = state
|
|
148
|
-
|
|
149
|
-
@override
|
|
150
|
-
@contextlib.asynccontextmanager
|
|
151
|
-
async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
|
|
152
|
-
"""Modify the state for a token while holding exclusive lock.
|
|
153
|
-
|
|
154
|
-
Args:
|
|
155
|
-
token: The token to modify the state for.
|
|
156
|
-
|
|
157
|
-
Yields:
|
|
158
|
-
The state for the token.
|
|
159
|
-
"""
|
|
160
|
-
# Memory state manager ignores the substate suffix and always returns the top-level state.
|
|
161
|
-
token = _split_substate_key(token)[0]
|
|
162
|
-
if token not in self._states_locks:
|
|
163
|
-
async with self._state_manager_lock:
|
|
164
|
-
if token not in self._states_locks:
|
|
165
|
-
self._states_locks[token] = asyncio.Lock()
|
|
166
|
-
|
|
167
|
-
async with self._states_locks[token]:
|
|
168
|
-
state = await self.get_state(token)
|
|
169
|
-
yield state
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
def _default_token_expiration() -> int:
|
|
173
|
-
"""Get the default token expiration time.
|
|
174
|
-
|
|
175
|
-
Returns:
|
|
176
|
-
The default token expiration time.
|
|
177
|
-
"""
|
|
178
|
-
return get_config().redis_token_expiration
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
def reset_disk_state_manager():
|
|
182
|
-
"""Reset the disk state manager."""
|
|
183
|
-
console.debug("Resetting disk state manager.")
|
|
184
|
-
states_directory = prerequisites.get_states_dir()
|
|
185
|
-
if states_directory.exists():
|
|
186
|
-
for path in states_directory.iterdir():
|
|
187
|
-
path.unlink()
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
@dataclasses.dataclass
|
|
191
|
-
class StateManagerDisk(StateManager):
|
|
192
|
-
"""A state manager that stores states in memory."""
|
|
193
|
-
|
|
194
|
-
# The mapping of client ids to states.
|
|
195
|
-
states: dict[str, BaseState] = dataclasses.field(default_factory=dict)
|
|
196
|
-
|
|
197
|
-
# The mutex ensures the dict of mutexes is updated exclusively
|
|
198
|
-
_state_manager_lock: asyncio.Lock = dataclasses.field(default=asyncio.Lock())
|
|
199
|
-
|
|
200
|
-
# The dict of mutexes for each client
|
|
201
|
-
_states_locks: dict[str, asyncio.Lock] = dataclasses.field(
|
|
202
|
-
default_factory=dict,
|
|
203
|
-
init=False,
|
|
204
|
-
)
|
|
205
|
-
|
|
206
|
-
# The token expiration time (s).
|
|
207
|
-
token_expiration: int = dataclasses.field(default_factory=_default_token_expiration)
|
|
208
|
-
|
|
209
|
-
def __post_init_(self):
|
|
210
|
-
"""Create a new state manager."""
|
|
211
|
-
path_ops.mkdir(self.states_directory)
|
|
212
|
-
|
|
213
|
-
self._purge_expired_states()
|
|
214
|
-
|
|
215
|
-
@functools.cached_property
|
|
216
|
-
def states_directory(self) -> Path:
|
|
217
|
-
"""Get the states directory.
|
|
218
|
-
|
|
219
|
-
Returns:
|
|
220
|
-
The states directory.
|
|
221
|
-
"""
|
|
222
|
-
return prerequisites.get_states_dir()
|
|
223
|
-
|
|
224
|
-
def _purge_expired_states(self):
|
|
225
|
-
"""Purge expired states from the disk."""
|
|
226
|
-
import time
|
|
227
|
-
|
|
228
|
-
for path in path_ops.ls(self.states_directory):
|
|
229
|
-
# check path is a pickle file
|
|
230
|
-
if path.suffix != ".pkl":
|
|
231
|
-
continue
|
|
232
|
-
|
|
233
|
-
# load last edited field from file
|
|
234
|
-
last_edited = path.stat().st_mtime
|
|
235
|
-
|
|
236
|
-
# check if the file is older than the token expiration time
|
|
237
|
-
if time.time() - last_edited > self.token_expiration:
|
|
238
|
-
# remove the file
|
|
239
|
-
path.unlink()
|
|
240
|
-
|
|
241
|
-
def token_path(self, token: str) -> Path:
|
|
242
|
-
"""Get the path for a token.
|
|
243
|
-
|
|
244
|
-
Args:
|
|
245
|
-
token: The token to get the path for.
|
|
246
|
-
|
|
247
|
-
Returns:
|
|
248
|
-
The path for the token.
|
|
249
|
-
"""
|
|
250
|
-
return (
|
|
251
|
-
self.states_directory / f"{md5(token.encode()).hexdigest()}.pkl"
|
|
252
|
-
).absolute()
|
|
253
|
-
|
|
254
|
-
async def load_state(self, token: str) -> BaseState | None:
|
|
255
|
-
"""Load a state object based on the provided token.
|
|
256
|
-
|
|
257
|
-
Args:
|
|
258
|
-
token: The token used to identify the state object.
|
|
259
|
-
|
|
260
|
-
Returns:
|
|
261
|
-
The loaded state object or None.
|
|
262
|
-
"""
|
|
263
|
-
token_path = self.token_path(token)
|
|
264
|
-
|
|
265
|
-
if token_path.exists():
|
|
266
|
-
try:
|
|
267
|
-
with token_path.open(mode="rb") as file:
|
|
268
|
-
return BaseState._deserialize(fp=file)
|
|
269
|
-
except Exception:
|
|
270
|
-
pass
|
|
271
|
-
return None
|
|
272
|
-
|
|
273
|
-
async def populate_substates(
|
|
274
|
-
self, client_token: str, state: BaseState, root_state: BaseState
|
|
275
|
-
):
|
|
276
|
-
"""Populate the substates of a state object.
|
|
277
|
-
|
|
278
|
-
Args:
|
|
279
|
-
client_token: The client token.
|
|
280
|
-
state: The state object to populate.
|
|
281
|
-
root_state: The root state object.
|
|
282
|
-
"""
|
|
283
|
-
for substate in state.get_substates():
|
|
284
|
-
substate_token = _substate_key(client_token, substate)
|
|
285
|
-
|
|
286
|
-
fresh_instance = await root_state.get_state(substate)
|
|
287
|
-
instance = await self.load_state(substate_token)
|
|
288
|
-
if instance is not None:
|
|
289
|
-
# Ensure all substates exist, even if they weren't serialized previously.
|
|
290
|
-
instance.substates = fresh_instance.substates
|
|
291
|
-
else:
|
|
292
|
-
instance = fresh_instance
|
|
293
|
-
state.substates[substate.get_name()] = instance
|
|
294
|
-
instance.parent_state = state
|
|
295
|
-
|
|
296
|
-
await self.populate_substates(client_token, instance, root_state)
|
|
297
|
-
|
|
298
|
-
@override
|
|
299
|
-
async def get_state(
|
|
300
|
-
self,
|
|
301
|
-
token: str,
|
|
302
|
-
) -> BaseState:
|
|
303
|
-
"""Get the state for a token.
|
|
304
|
-
|
|
305
|
-
Args:
|
|
306
|
-
token: The token to get the state for.
|
|
307
|
-
|
|
308
|
-
Returns:
|
|
309
|
-
The state for the token.
|
|
310
|
-
"""
|
|
311
|
-
client_token = _split_substate_key(token)[0]
|
|
312
|
-
root_state = self.states.get(client_token)
|
|
313
|
-
if root_state is not None:
|
|
314
|
-
# Retrieved state from memory.
|
|
315
|
-
return root_state
|
|
316
|
-
|
|
317
|
-
# Deserialize root state from disk.
|
|
318
|
-
root_state = await self.load_state(_substate_key(client_token, self.state))
|
|
319
|
-
# Create a new root state tree with all substates instantiated.
|
|
320
|
-
fresh_root_state = self.state(_reflex_internal_init=True)
|
|
321
|
-
if root_state is None:
|
|
322
|
-
root_state = fresh_root_state
|
|
323
|
-
else:
|
|
324
|
-
# Ensure all substates exist, even if they were not serialized previously.
|
|
325
|
-
root_state.substates = fresh_root_state.substates
|
|
326
|
-
self.states[client_token] = root_state
|
|
327
|
-
await self.populate_substates(client_token, root_state, root_state)
|
|
328
|
-
return root_state
|
|
329
|
-
|
|
330
|
-
async def set_state_for_substate(self, client_token: str, substate: BaseState):
|
|
331
|
-
"""Set the state for a substate.
|
|
332
|
-
|
|
333
|
-
Args:
|
|
334
|
-
client_token: The client token.
|
|
335
|
-
substate: The substate to set.
|
|
336
|
-
"""
|
|
337
|
-
substate_token = _substate_key(client_token, substate)
|
|
338
|
-
|
|
339
|
-
if substate._get_was_touched():
|
|
340
|
-
substate._was_touched = False # Reset the touched flag after serializing.
|
|
341
|
-
pickle_state = substate._serialize()
|
|
342
|
-
if pickle_state:
|
|
343
|
-
if not self.states_directory.exists():
|
|
344
|
-
self.states_directory.mkdir(parents=True, exist_ok=True)
|
|
345
|
-
self.token_path(substate_token).write_bytes(pickle_state)
|
|
346
|
-
|
|
347
|
-
for substate_substate in substate.substates.values():
|
|
348
|
-
await self.set_state_for_substate(client_token, substate_substate)
|
|
349
|
-
|
|
350
|
-
@override
|
|
351
|
-
async def set_state(self, token: str, state: BaseState):
|
|
352
|
-
"""Set the state for a token.
|
|
353
|
-
|
|
354
|
-
Args:
|
|
355
|
-
token: The token to set the state for.
|
|
356
|
-
state: The state to set.
|
|
357
|
-
"""
|
|
358
|
-
client_token, _ = _split_substate_key(token)
|
|
359
|
-
await self.set_state_for_substate(client_token, state)
|
|
360
|
-
|
|
361
|
-
@override
|
|
362
|
-
@contextlib.asynccontextmanager
|
|
363
|
-
async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
|
|
364
|
-
"""Modify the state for a token while holding exclusive lock.
|
|
365
|
-
|
|
366
|
-
Args:
|
|
367
|
-
token: The token to modify the state for.
|
|
368
|
-
|
|
369
|
-
Yields:
|
|
370
|
-
The state for the token.
|
|
371
|
-
"""
|
|
372
|
-
# Memory state manager ignores the substate suffix and always returns the top-level state.
|
|
373
|
-
client_token, _ = _split_substate_key(token)
|
|
374
|
-
if client_token not in self._states_locks:
|
|
375
|
-
async with self._state_manager_lock:
|
|
376
|
-
if client_token not in self._states_locks:
|
|
377
|
-
self._states_locks[client_token] = asyncio.Lock()
|
|
378
|
-
|
|
379
|
-
async with self._states_locks[client_token]:
|
|
380
|
-
state = await self.get_state(token)
|
|
381
|
-
yield state
|
|
382
|
-
await self.set_state(token, state)
|
|
383
|
-
|
|
384
|
-
|
|
385
27
|
def _default_lock_expiration() -> int:
|
|
386
28
|
"""Get the default lock expiration time.
|
|
387
29
|
|
|
@@ -748,7 +390,7 @@ class StateManagerRedis(StateManager):
|
|
|
748
390
|
if timeout is None:
|
|
749
391
|
timeout = self.lock_expiration / 1000.0
|
|
750
392
|
|
|
751
|
-
started = time.
|
|
393
|
+
started = time.monotonic()
|
|
752
394
|
message = await pubsub.get_message(
|
|
753
395
|
ignore_subscribe_messages=True,
|
|
754
396
|
timeout=timeout,
|
|
@@ -757,7 +399,7 @@ class StateManagerRedis(StateManager):
|
|
|
757
399
|
message is None
|
|
758
400
|
or message["data"] not in self._redis_keyspace_lock_release_events
|
|
759
401
|
):
|
|
760
|
-
remaining = timeout - (time.
|
|
402
|
+
remaining = timeout - (time.monotonic() - started)
|
|
761
403
|
if remaining <= 0:
|
|
762
404
|
return
|
|
763
405
|
await self._get_pubsub_message(pubsub, timeout=remaining)
|
|
@@ -847,12 +489,3 @@ class StateManagerRedis(StateManager):
|
|
|
847
489
|
Note: Connections will be automatically reopened when needed.
|
|
848
490
|
"""
|
|
849
491
|
await self.redis.aclose(close_connection_pool=True)
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
def get_state_manager() -> StateManager:
|
|
853
|
-
"""Get the state manager for the app that is currently running.
|
|
854
|
-
|
|
855
|
-
Returns:
|
|
856
|
-
The state manager.
|
|
857
|
-
"""
|
|
858
|
-
return prerequisites.get_and_validate_app().app.state_manager
|
reflex/istate/proxy.py
CHANGED
|
@@ -9,19 +9,16 @@ import functools
|
|
|
9
9
|
import inspect
|
|
10
10
|
import json
|
|
11
11
|
from collections.abc import Callable, Sequence
|
|
12
|
+
from importlib.util import find_spec
|
|
12
13
|
from types import MethodType
|
|
13
14
|
from typing import TYPE_CHECKING, Any, SupportsIndex, TypeVar
|
|
14
15
|
|
|
15
|
-
import pydantic
|
|
16
16
|
import wrapt
|
|
17
|
-
from pydantic import BaseModel as BaseModelV2
|
|
18
|
-
from pydantic.v1 import BaseModel as BaseModelV1
|
|
19
|
-
from sqlalchemy.orm import DeclarativeBase
|
|
20
17
|
|
|
21
18
|
from reflex.base import Base
|
|
22
19
|
from reflex.utils import prerequisites
|
|
23
20
|
from reflex.utils.exceptions import ImmutableStateError
|
|
24
|
-
from reflex.utils.serializers import serializer
|
|
21
|
+
from reflex.utils.serializers import can_serialize, serialize, serializer
|
|
25
22
|
from reflex.vars.base import Var
|
|
26
23
|
|
|
27
24
|
if TYPE_CHECKING:
|
|
@@ -339,6 +336,34 @@ class ReadOnlyStateProxy(StateProxy):
|
|
|
339
336
|
raise NotImplementedError(msg)
|
|
340
337
|
|
|
341
338
|
|
|
339
|
+
if find_spec("pydantic"):
|
|
340
|
+
import pydantic
|
|
341
|
+
|
|
342
|
+
NEVER_WRAP_BASE_ATTRS = set(Base.__dict__) - {"set"} | set(
|
|
343
|
+
pydantic.BaseModel.__dict__
|
|
344
|
+
)
|
|
345
|
+
else:
|
|
346
|
+
NEVER_WRAP_BASE_ATTRS = {}
|
|
347
|
+
|
|
348
|
+
MUTABLE_TYPES = (
|
|
349
|
+
list,
|
|
350
|
+
dict,
|
|
351
|
+
set,
|
|
352
|
+
Base,
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
if find_spec("sqlalchemy"):
|
|
356
|
+
from sqlalchemy.orm import DeclarativeBase
|
|
357
|
+
|
|
358
|
+
MUTABLE_TYPES += (DeclarativeBase,)
|
|
359
|
+
|
|
360
|
+
if find_spec("pydantic"):
|
|
361
|
+
from pydantic import BaseModel as BaseModelV2
|
|
362
|
+
from pydantic.v1 import BaseModel as BaseModelV1
|
|
363
|
+
|
|
364
|
+
MUTABLE_TYPES += (BaseModelV1, BaseModelV2)
|
|
365
|
+
|
|
366
|
+
|
|
342
367
|
class MutableProxy(wrapt.ObjectProxy):
|
|
343
368
|
"""A proxy for a mutable object that tracks changes."""
|
|
344
369
|
|
|
@@ -371,11 +396,6 @@ class MutableProxy(wrapt.ObjectProxy):
|
|
|
371
396
|
"setdefault",
|
|
372
397
|
}
|
|
373
398
|
|
|
374
|
-
# These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
|
|
375
|
-
__never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
|
|
376
|
-
pydantic.BaseModel.__dict__
|
|
377
|
-
)
|
|
378
|
-
|
|
379
399
|
# Dynamically generated classes for tracking dataclass mutations.
|
|
380
400
|
__dataclass_proxies__: dict[type, type] = {}
|
|
381
401
|
|
|
@@ -539,7 +559,7 @@ class MutableProxy(wrapt.ObjectProxy):
|
|
|
539
559
|
|
|
540
560
|
if (
|
|
541
561
|
isinstance(self.__wrapped__, Base)
|
|
542
|
-
and __name not in
|
|
562
|
+
and __name not in NEVER_WRAP_BASE_ATTRS
|
|
543
563
|
and hasattr(value, "__func__")
|
|
544
564
|
):
|
|
545
565
|
# Wrap methods called on Base subclasses, which might do _anything_
|
|
@@ -669,7 +689,10 @@ def serialize_mutable_proxy(mp: MutableProxy):
|
|
|
669
689
|
Returns:
|
|
670
690
|
The wrapped object.
|
|
671
691
|
"""
|
|
672
|
-
|
|
692
|
+
obj = mp.__wrapped__
|
|
693
|
+
if can_serialize(type(obj)):
|
|
694
|
+
return serialize(obj)
|
|
695
|
+
return obj
|
|
673
696
|
|
|
674
697
|
|
|
675
698
|
_orig_json_encoder_default = json.JSONEncoder.default
|
|
@@ -739,18 +762,6 @@ class ImmutableMutableProxy(MutableProxy):
|
|
|
739
762
|
)
|
|
740
763
|
|
|
741
764
|
|
|
742
|
-
# These types will be wrapped in MutableProxy
|
|
743
|
-
MUTABLE_TYPES = (
|
|
744
|
-
list,
|
|
745
|
-
dict,
|
|
746
|
-
set,
|
|
747
|
-
Base,
|
|
748
|
-
DeclarativeBase,
|
|
749
|
-
BaseModelV2,
|
|
750
|
-
BaseModelV1,
|
|
751
|
-
)
|
|
752
|
-
|
|
753
|
-
|
|
754
765
|
@functools.lru_cache(maxsize=1024)
|
|
755
766
|
def is_mutable_type(type_: type) -> bool:
|
|
756
767
|
"""Check if a type is mutable and should be wrapped.
|