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

Add session_check and session_id_getter to serverside #340

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
14 changes: 10 additions & 4 deletions dash_extensions/enrich.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,8 @@ def layout(self, value):
self.blueprint.layout = value


def _get_session_id(session_key=None):
session_key = "session_id" if session_key is None else session_key
def _get_serverside_session_id(session_key=None):
session_key = "serverside_session_id" if session_key is None else session_key
# Create unique session id.
if not session.get(session_key):
session[session_key] = secrets.token_urlsafe(16)
Expand Down Expand Up @@ -1404,6 +1404,8 @@ def __init__(
self,
backends: Optional[List[ServersideBackend]] = None,
default_backend: Optional[ServersideBackend] = None,
session_check: Optional[bool] = False,
session_id_getter: Callable = _get_serverside_session_id,
):
super().__init__()
# Per default, use file system backend.
Expand All @@ -1412,6 +1414,8 @@ def __init__(
self._default_backend: ServersideBackend = backends[0] if default_backend is None else default_backend
# Setup registry for easy/fast access.
self._backend_registry: Dict[str, ServersideBackend] = {backend.uid: backend for backend in backends}
self._session_check = session_check
self._session_id_getter = session_id_getter

def _try_load(self, data: Any, ann=None) -> Any:
if not isinstance(data, str):
Expand All @@ -1420,7 +1424,8 @@ def _try_load(self, data: Any, ann=None) -> Any:
return data
obj = json.loads(data[len(self.prefix) :])
backend = self._backend_registry[obj["backend_uid"]]
value = backend.get(obj["key"], ignore_expired=True)
cached_item_key = f"{obj["key"]}-{self._session_id_getter()}" if self._session_check else obj["key"]
value = backend.get(cached_item_key, ignore_expired=True)
return value

def _try_dump(self, obj: Any) -> Any:
Expand All @@ -1432,7 +1437,8 @@ def _try_dump(self, obj: Any) -> Any:
backend_uid = self._default_backend.uid
# Dump the data.
backend = self._backend_registry[backend_uid]
backend.set(obj.key, obj.value)
cached_item_key = f"{obj["key"]}-{self._session_id_getter()}" if self._session_check else obj.key
backend.set(cached_item_key, obj.value)
# Return lookup structure.
data = dict(backend_uid=backend_uid, key=obj.key)
return f"{self.prefix}{json.dumps(data)}"
Expand Down
Loading