Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[REF-2045] Implement __reduce_ex__ for MutableProxy #2688

Merged
merged 3 commits into from
Feb 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions reflex/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ def get_value(self, key: str) -> Any:
Returns:
The value of the field.
"""
if isinstance(key, str) and key in self.__fields__:
# Seems like this function signature was wrong all along?
# If the user wants a field that we know of, get it and pass it off to _get_value
key = getattr(self, key)
return self._get_value(
key,
to_dict=True,
Expand Down
15 changes: 15 additions & 0 deletions reflex/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -2363,6 +2363,21 @@ def __deepcopy__(self, memo=None) -> Any:
"""
return copy.deepcopy(self.__wrapped__, memo=memo)

def __reduce_ex__(self, protocol_version):
"""Get the state for redis serialization.

This method is called by cloudpickle to serialize the object.

It explicitly serializes the wrapped object, stripping off the mutable proxy.

Args:
protocol_version: The protocol version.

Returns:
Tuple of (wrapped class, empty args, class __getstate__)
"""
return self.__wrapped__.__reduce_ex__(protocol_version)


@serializer
def serialize_mutable_proxy(mp: MutableProxy) -> SerializedType:
Expand Down
6 changes: 5 additions & 1 deletion tests/test_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1457,12 +1457,16 @@ async def test_state_manager_modify_state(
token: A token.
substate_token: A token + substate name for looking up in state manager.
"""
async with state_manager.modify_state(substate_token):
async with state_manager.modify_state(substate_token) as state:
if isinstance(state_manager, StateManagerRedis):
assert await state_manager.redis.get(f"{token}_lock")
elif isinstance(state_manager, StateManagerMemory):
assert token in state_manager._states_locks
assert state_manager._states_locks[token].locked()
# Should be able to write proxy objects inside mutables
complex_1 = state.complex[1]
assert isinstance(complex_1, MutableProxy)
state.complex[3] = complex_1
# lock should be dropped after exiting the context
if isinstance(state_manager, StateManagerRedis):
assert (await state_manager.redis.get(f"{token}_lock")) is None
Expand Down
Loading