-
Notifications
You must be signed in to change notification settings - Fork 0
Add Streamlit state helpers for query parameters #30
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
Open
felipeimpieri
wants to merge
1
commit into
codex/shared-state-clean
Choose a base branch
from
codex/add-state-management-in-quantboard/ui
base: codex/shared-state-clean
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| """Utilities for synchronizing URL query params with Streamlit session state.""" | ||
|
|
||
| from typing import Any, Dict | ||
|
|
||
| import streamlit as st | ||
|
|
||
|
|
||
| def _coerce_type(value: Any, default: Any) -> Any: | ||
| """Cast value to the type of default, falling back to default on failure.""" | ||
| if value is None: | ||
| return default | ||
|
|
||
| target_type = type(default) | ||
|
|
||
| if isinstance(value, list): | ||
| if not value: | ||
| return default | ||
| value = value[0] | ||
|
|
||
| if target_type is type(None): | ||
| return None | ||
|
|
||
| if isinstance(value, target_type): | ||
| return value | ||
|
|
||
| try: | ||
| if target_type is bool: | ||
| if isinstance(value, str): | ||
| lowered = value.strip().lower() | ||
| if lowered in {"true", "1", "yes", "y", "on", "t"}: | ||
| return True | ||
| if lowered in {"false", "0", "no", "n", "off", "f"}: | ||
| return False | ||
| return bool(value) | ||
|
|
||
| return target_type(value) | ||
| except Exception: | ||
| return default | ||
|
|
||
|
|
||
| def _get_query_params() -> Dict[str, Any]: | ||
| """Return query params supporting both the new and experimental Streamlit APIs.""" | ||
| try: | ||
| params = st.query_params | ||
| if callable(getattr(params, "to_dict", None)): | ||
| params = params.to_dict() | ||
| else: | ||
| params = dict(params) | ||
| return {k: v for k, v in params.items()} | ||
| except Exception: | ||
| pass | ||
|
|
||
| try: | ||
| return st.experimental_get_query_params() | ||
| except Exception: | ||
| return {} | ||
|
|
||
|
|
||
| def _set_query_params(params: Dict[str, Any]) -> None: | ||
| """Merge and set query params across the available Streamlit APIs.""" | ||
| current = _get_query_params() | ||
| merged = {**current, **params} | ||
|
|
||
| def _normalize(value: Any) -> Any: | ||
| if isinstance(value, list): | ||
| return [str(v) for v in value] | ||
| if value is None: | ||
| return "" | ||
| return str(value) | ||
|
|
||
| normalized = {k: _normalize(v) for k, v in merged.items()} | ||
|
|
||
| try: | ||
| st.query_params = normalized | ||
| return | ||
| except Exception: | ||
| pass | ||
|
|
||
| try: | ||
| st.experimental_set_query_params(**normalized) | ||
| except Exception: | ||
| return | ||
|
|
||
|
|
||
| def get_param(key: str, default: Any) -> Any: | ||
| """Fetch a parameter from the URL, falling back to session state or default.""" | ||
| params = _get_query_params() | ||
| value = params.get(key) | ||
|
|
||
| if value is None: | ||
| if key in st.session_state: | ||
| value = st.session_state[key] | ||
| else: | ||
| value = default | ||
|
|
||
| coerced = _coerce_type(value, default) | ||
| st.session_state[key] = coerced | ||
| return coerced | ||
|
|
||
|
|
||
| def set_param(key: str, value: Any) -> None: | ||
| """Update a parameter in session state and the URL query string.""" | ||
| st.session_state[key] = value | ||
| _set_query_params({key: value}) | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_coerce_typeshort-circuits whenever the default isNone, returningNoneeven if a query param or existing session-state value is present. Anyget_param("foo", None)call will therefore overwrite a suppliedfooquery string or previously set session state withNone, preventing optional parameters from ever being read. The helper should only fall back toNonewhen the incoming value is absent or cannot be coerced, not unconditionally discard it.Useful? React with 👍 / 👎.