reflex/reflex/middleware/hydrate_middleware.py
Thomas Brandého 0d39237b3c
upgrade to latest ruff (#3497)
* upgrade to latest ruff

* try to fix dep review

* try to fix dep review (2)

* upgrade black

* upgrade black (2)

* update allowed dependencies

* update allowed dependencies (2)

* update allowed dependencies (3)

* wait between interim and final in yield test

* remove previous commit, increase delay between yield

* forgot to save on the time.sleep(1) removal

* fix integration (maybe?)

* fix pyi?

* what even is going on

* what is realityi?

* test another fix for app harness

* try to wait even longer?

* force uvloop to be optional

* downpin fastapi < 0.111, remove changes to test
2024-06-19 12:32:13 +02:00

50 lines
1.5 KiB
Python

"""Middleware to hydrate the state."""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from reflex import constants
from reflex.event import Event, get_hydrate_event
from reflex.middleware.middleware import Middleware
from reflex.state import BaseState, StateUpdate
from reflex.utils import format
if TYPE_CHECKING:
from reflex.app import App
class HydrateMiddleware(Middleware):
"""Middleware to handle initial app hydration."""
async def preprocess(
self, app: App, state: BaseState, event: Event
) -> Optional[StateUpdate]:
"""Preprocess the event.
Args:
app: The app to apply the middleware to.
state: The client state.
event: The event to preprocess.
Returns:
An optional delta or list of state updates to return.
"""
# If this is not the hydrate event, return None
if event.name != get_hydrate_event(state):
return None
# Clear client storage, to respect clearing cookies
state._reset_client_storage()
# Mark state as not hydrated (until on_loads are complete)
setattr(state, constants.CompileVars.IS_HYDRATED, False)
# Get the initial state.
delta = format.format_state(state.dict())
# since a full dict was captured, clean any dirtiness
state._clean()
# Return the state update.
return StateUpdate(delta=delta, events=[])