Dataset Viewer
Auto-converted to Parquet Duplicate
index
int64
0
0
repo_id
stringclasses
80 values
file_path
stringlengths
32
137
content
stringlengths
4
914k
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/experimental_query_params.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Any from urllib import parse from streamlit.errors import StreamlitAPIException from streamlit.proto.ForwardMsg_pb2 import ForwardMsg from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx from streamlit.runtime.state.query_params import ( EMBED_OPTIONS_QUERY_PARAM, EMBED_QUERY_PARAM, EMBED_QUERY_PARAMS_KEYS, ) @gather_metrics("experimental_get_query_params") def get_query_params() -> dict[str, list[str]]: """Return the query parameters that is currently showing in the browser's URL bar. Returns ------- dict The current query parameters as a dict. "Query parameters" are the part of the URL that comes after the first "?". Example ------- Let's say the user's web browser is at `http://localhost:8501/?show_map=True&selected=asia&selected=america`. Then, you can get the query parameters using the following: >>> import streamlit as st >>> >>> st.experimental_get_query_params() {"show_map": ["True"], "selected": ["asia", "america"]} Note that the values in the returned dict are *always* lists. This is because we internally use Python's urllib.parse.parse_qs(), which behaves this way. And this behavior makes sense when you consider that every item in a query string is potentially a 1-element array. """ ctx = get_script_run_ctx() if ctx is None: return {} ctx.mark_experimental_query_params_used() # Return new query params dict, but without embed, embed_options query params return _exclude_keys_in_dict( parse.parse_qs(ctx.query_string, keep_blank_values=True), keys_to_exclude=EMBED_QUERY_PARAMS_KEYS, ) @gather_metrics("experimental_set_query_params") def set_query_params(**query_params: Any) -> None: """Set the query parameters that are shown in the browser's URL bar. .. warning:: Query param `embed` cannot be set using this method. Parameters ---------- **query_params : dict The query parameters to set, as key-value pairs. Example ------- To point the user's web browser to something like "http://localhost:8501/?show_map=True&selected=asia&selected=america", you would do the following: >>> import streamlit as st >>> >>> st.experimental_set_query_params( ... show_map=True, ... selected=["asia", "america"], ... ) """ ctx = get_script_run_ctx() if ctx is None: return ctx.mark_experimental_query_params_used() msg = ForwardMsg() msg.page_info_changed.query_string = _ensure_no_embed_params( query_params, ctx.query_string ) ctx.query_string = msg.page_info_changed.query_string ctx.enqueue(msg) def _exclude_keys_in_dict( d: dict[str, Any], keys_to_exclude: list[str] ) -> dict[str, Any]: """Returns new object but without keys defined in keys_to_exclude.""" return { key: value for key, value in d.items() if key.lower() not in keys_to_exclude } def _extract_key_query_params( query_params: dict[str, list[str]], param_key: str ) -> set[str]: """Extracts key (case-insensitive) query params from Dict, and returns them as Set of str.""" return { item.lower() for sublist in [ [value.lower() for value in query_params[key]] for key in query_params if key.lower() == param_key and query_params.get(key) ] for item in sublist } def _ensure_no_embed_params( query_params: dict[str, list[str] | str], query_string: str ) -> str: """Ensures there are no embed params set (raises StreamlitAPIException) if there is a try, also makes sure old param values in query_string are preserved. Returns query_string : str. """ # Get query params dict without embed, embed_options params query_params_without_embed = _exclude_keys_in_dict( query_params, keys_to_exclude=EMBED_QUERY_PARAMS_KEYS ) if query_params != query_params_without_embed: raise StreamlitAPIException( "Query param embed and embed_options (case-insensitive) cannot be set using set_query_params method." ) all_current_params = parse.parse_qs(query_string, keep_blank_values=True) current_embed_params = parse.urlencode( { EMBED_QUERY_PARAM: list( _extract_key_query_params( all_current_params, param_key=EMBED_QUERY_PARAM ) ), EMBED_OPTIONS_QUERY_PARAM: list( _extract_key_query_params( all_current_params, param_key=EMBED_OPTIONS_QUERY_PARAM ) ), }, doseq=True, ) query_string = parse.urlencode(query_params, doseq=True) if query_string: separator = "&" if current_embed_params else "" return separator.join([query_string, current_embed_params]) return current_embed_params
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/execution_control.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import time from collections.abc import Iterable, Mapping from itertools import dropwhile from pathlib import Path from typing import TYPE_CHECKING, Literal, NoReturn import streamlit as st from streamlit.errors import NoSessionContext, StreamlitAPIException from streamlit.file_util import get_main_script_directory, normalize_path_join from streamlit.navigation.page import StreamlitPage from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner import ( RerunData, ScriptRunContext, get_script_run_ctx, ) if TYPE_CHECKING: from streamlit.runtime.state.query_params import QueryParams, QueryParamsInput @gather_metrics("stop") def stop() -> NoReturn: # type: ignore[misc] """Stops execution immediately. Streamlit will not run any statements after `st.stop()`. We recommend rendering a message to explain why the script has stopped. Example ------- >>> import streamlit as st >>> >>> name = st.text_input("Name") >>> if not name: >>> st.warning('Please input a name.') >>> st.stop() >>> st.success("Thank you for inputting a name.") """ ctx = get_script_run_ctx() if ctx and ctx.script_requests: ctx.script_requests.request_stop() # Force a yield point so the runner can stop st.empty() def _new_fragment_id_queue( ctx: ScriptRunContext, scope: Literal["app", "fragment"], ) -> list[str]: if scope == "app": return [] # > scope == "fragment" curr_queue = ctx.fragment_ids_this_run # If st.rerun(scope="fragment") is called during a full script run, we raise an # exception. This occurs, of course, if st.rerun(scope="fragment") is called # outside of a fragment, but it somewhat surprisingly occurs if it gets called # from within a fragment during a run of the full script. While this behavior may # be surprising, it seems somewhat reasonable given that the correct behavior of # calling st.rerun(scope="fragment") in this situation is unclear to me: # * Rerunning just the fragment immediately may cause weirdness down the line # as any part of the script that occurs after the fragment will not be # executed. # * Waiting until the full script run completes before rerunning the fragment # seems odd (even if we normally do this before running a fragment not # triggered by st.rerun()) because it defers the execution of st.rerun(). # * Rerunning the full app feels incorrect as we're seemingly ignoring the # `scope` argument. # With these issues and given that it seems pretty unnatural to have a # fragment-scoped rerun happen during a full script run to begin with, it seems # reasonable to just disallow this completely for now. if not curr_queue: raise StreamlitAPIException( 'scope="fragment" can only be specified from `@st.fragment`-decorated ' "functions during fragment reruns." ) new_queue = list(dropwhile(lambda x: x != ctx.current_fragment_id, curr_queue)) if not new_queue: raise RuntimeError( "Could not find current_fragment_id in fragment_id_queue. This should never happen." ) return new_queue def _set_query_params_for_switch( query_params_state: QueryParams, new_query_params: QueryParamsInput | None, ) -> None: """Set query params for a switch page.""" if new_query_params is None: query_params_state.clear() return if isinstance(new_query_params, Mapping) or ( isinstance(new_query_params, Iterable) and not isinstance( new_query_params, # type: ignore[unreachable] (str, bytes), ) ): query_params_state.from_dict(new_query_params) return raise StreamlitAPIException( f"`query_params` must be a mapping or an iterable of (key, value) pairs not a `{type(new_query_params)}`." ) @gather_metrics("rerun") def rerun( # type: ignore[misc] *, # The scope argument can only be passed via keyword. scope: Literal["app", "fragment"] = "app", ) -> NoReturn: # ty: ignore[invalid-return-type] """Rerun the script immediately. When ``st.rerun()`` is called, Streamlit halts the current script run and executes no further statements. Streamlit immediately queues the script to rerun. When using ``st.rerun`` in a fragment, you can scope the rerun to the fragment. However, if a fragment is running as part of a full-app rerun, a fragment-scoped rerun is not allowed. Parameters ---------- scope : "app" or "fragment" Specifies what part of the app should rerun. If ``scope`` is ``"app"`` (default), the full app reruns. If ``scope`` is ``"fragment"``, Streamlit only reruns the fragment from which this command is called. Setting ``scope="fragment"`` is only valid inside a fragment during a fragment rerun. If ``st.rerun(scope="fragment")`` is called during a full-app rerun or outside of a fragment, Streamlit will raise a ``StreamlitAPIException``. """ if scope not in ["app", "fragment"]: raise StreamlitAPIException( f"'{scope}'is not a valid rerun scope. Valid scopes are 'app' and 'fragment'." ) ctx = get_script_run_ctx() if ctx and ctx.script_requests: query_string = ctx.query_string page_script_hash = ctx.page_script_hash cached_message_hashes = ctx.cached_message_hashes ctx.script_requests.request_rerun( RerunData( query_string=query_string, page_script_hash=page_script_hash, fragment_id_queue=_new_fragment_id_queue(ctx, scope), is_fragment_scoped_rerun=scope == "fragment", cached_message_hashes=cached_message_hashes, context_info=ctx.context_info, ) ) # Force a yield point so the runner can do the rerun st.empty() @gather_metrics("switch_page") def switch_page( # type: ignore[misc] page: str | Path | StreamlitPage, *, query_params: QueryParamsInput | None = None, ) -> NoReturn: # ty: ignore[invalid-return-type] """Programmatically switch the current page in a multipage app. When ``st.switch_page`` is called, the current page execution stops and the specified page runs as if the user clicked on it in the sidebar navigation. The specified page must be recognized by Streamlit's multipage architecture (your main Python file or a Python file in a ``pages/`` folder). Arbitrary Python scripts cannot be passed to ``st.switch_page``. Parameters ---------- page : str, Path, or st.Page The file path (relative to the main script) or an st.Page indicating the page to switch to. query_params : dict, list of tuples, or None Query parameters to apply when navigating to the target page. This can be a dictionary or an iterable of key-value tuples. Values can be strings or iterables of strings (for repeated keys). When this is ``None`` (default), all non-embed query parameters are cleared during navigation. Examples -------- **Example 1: Basic usage** The following example shows how to switch to a different page in a multipage app that uses the ``pages/`` directory: .. code-block:: text your-repository/ ├── pages/ │ ├── page_1.py │ └── page_2.py └── your_app.py >>> import streamlit as st >>> >>> if st.button("Home"): >>> st.switch_page("your_app.py") >>> if st.button("Page 1"): >>> st.switch_page("pages/page_1.py") >>> if st.button("Page 2"): >>> st.switch_page("pages/page_2.py") .. output:: https://doc-switch-page.streamlit.app/ height: 350px **Example 2: Passing query parameters** The following example shows how to pass query parameters when switching to a different page. This example uses ``st.navigation`` to create a multipage app. .. code-block:: text your-repository/ ├── page_2.py └── your_app.py >>> import streamlit as st >>> >>> def page_1(): >>> st.title("Page 1") >>> if st.button("Switch to Page 2"): >>> st.switch_page("page_2.py", query_params={"utm_source": "page_1"}) >>> >>> pg = st.navigation([page_1, "page_2.py"]) >>> pg.run() .. output:: https://doc-switch-page-query-params.streamlit.app/ height: 350px """ ctx = get_script_run_ctx() if not ctx or not ctx.script_requests: # This should never be the case raise NoSessionContext() page_script_hash = "" if isinstance(page, StreamlitPage): page_script_hash = page._script_hash else: # Convert Path to string if necessary if isinstance(page, Path): page = str(page) main_script_directory = get_main_script_directory(ctx.main_script_path) requested_page = os.path.realpath( normalize_path_join(main_script_directory, page) ) all_app_pages = ctx.pages_manager.get_pages().values() matched_pages = [p for p in all_app_pages if p["script_path"] == requested_page] if len(matched_pages) == 0: raise StreamlitAPIException( f"Could not find page: `{page}`. Must be the file path relative to the main script, " f"from the directory: `{os.path.basename(main_script_directory)}`. Only the main app file " "and files in the `pages/` directory are supported." ) page_script_hash = matched_pages[0]["page_script_hash"] # Reset query params (with exception of embed) and optionally apply overrides. with ctx.session_state.query_params() as qp: _set_query_params_for_switch(qp, query_params) # Additional safeguard to ensure the query params # are sent out to the frontend before the new rerun might clear # outstanding messages. This uses the same time that is used as waiting # in our event loop. time.sleep(0.01) ctx.script_requests.request_rerun( RerunData( query_string=ctx.query_string, page_script_hash=page_script_hash, cached_message_hashes=ctx.cached_message_hashes, context_info=ctx.context_info, ) ) # Force a yield point so the runner can do the rerun st.empty()
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/navigation.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from collections.abc import Callable, Mapping, Sequence from pathlib import Path from typing import TYPE_CHECKING, Literal, TypeAlias from streamlit import config from streamlit.errors import StreamlitAPIException from streamlit.navigation.page import StreamlitPage from streamlit.proto.ForwardMsg_pb2 import ForwardMsg from streamlit.proto.Navigation_pb2 import Navigation as NavigationProto from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.pages_manager import PagesManager from streamlit.runtime.scriptrunner_utils.script_run_context import ( ScriptRunContext, get_script_run_ctx, ) from streamlit.string_util import is_emoji if TYPE_CHECKING: from streamlit.source_util import PageHash, PageInfo SectionHeader: TypeAlias = str PageType: TypeAlias = str | Path | Callable[[], None] | StreamlitPage def convert_to_streamlit_page( page_input: PageType, ) -> StreamlitPage: """Convert various input types to StreamlitPage objects.""" if isinstance(page_input, StreamlitPage): return page_input if isinstance(page_input, str): return StreamlitPage(page_input) if isinstance(page_input, Path): return StreamlitPage(page_input) if callable(page_input): # Convert function to StreamlitPage return StreamlitPage(page_input) raise StreamlitAPIException( f"Invalid page type: {type(page_input)}. Must be either a string path, " "a pathlib.Path, a callable function, or a st.Page object." ) def pages_from_nav_sections( nav_sections: dict[SectionHeader, list[StreamlitPage]], ) -> list[StreamlitPage]: page_list = [] for pages in nav_sections.values(): page_list.extend(pages.copy()) return page_list def send_page_not_found(ctx: ScriptRunContext) -> None: msg = ForwardMsg() msg.page_not_found.page_name = "" ctx.enqueue(msg) @gather_metrics("navigation") def navigation( pages: Sequence[PageType] | Mapping[SectionHeader, Sequence[PageType]], *, position: Literal["sidebar", "hidden", "top"] = "sidebar", expanded: bool = False, ) -> StreamlitPage: """ Configure the available pages in a multipage app. Call ``st.navigation`` in your entrypoint file to define the available pages for your app. ``st.navigation`` returns the current page, which can be executed using ``.run()`` method. When using ``st.navigation``, your entrypoint file (the file passed to ``streamlit run``) acts like a router or frame of common elements around each of your pages. Streamlit executes the entrypoint file with every app rerun. To execute the current page, you must call the ``.run()`` method on the ``StreamlitPage`` object returned by ``st.navigation``. The set of available pages can be updated with each rerun for dynamic navigation. By default, ``st.navigation`` displays the available pages in the sidebar if there is more than one page. This behavior can be changed using the ``position`` keyword argument. As soon as any session of your app executes the ``st.navigation`` command, your app will ignore the ``pages/`` directory (across all sessions). Parameters ---------- pages : Sequence[page-like], Mapping[str, Sequence[page-like]] The available pages for the app. To create a navigation menu with no sections or page groupings, ``pages`` must be a list of page-like objects. Page-like objects are anything that can be passed to ``st.Page`` or a ``StreamlitPage`` object returned by ``st.Page``. To create labeled sections or page groupings within the navigation menu, ``pages`` must be a dictionary. Each key is the label of a section and each value is the list of page-like objects for that section. If you use ``position="top"``, each grouping will be a collapsible item in the navigation menu. For top navigation, if you use an empty string as a section header, the pages in that section will be displayed at the beginning of the menu before the collapsible sections. When you use a string or path as a page-like object, they are internally passed to ``st.Page`` and converted to ``StreamlitPage`` objects. In this case, the page will have the default title, icon, and path inferred from its path or filename. To customize these attributes for your page, initialize your page with ``st.Page``. position : "sidebar", "top", or "hidden" The position of the navigation menu. If this is ``"sidebar"`` (default), the navigation widget appears at the top of the sidebar. If this is ``"top"``, the navigation appears in the top header of the app. If this is ``"hidden"``, the navigation widget is not displayed. If there is only one page in ``pages``, the navigation will be hidden for any value of ``position``. expanded : bool Whether the navigation menu should be expanded. If this is ``False`` (default), the navigation menu will be collapsed and will include a button to view more options when there are too many pages to display. If this is ``True``, the navigation menu will always be expanded; no button to collapse the menu will be displayed. If ``st.navigation`` changes from ``expanded=True`` to ``expanded=False`` on a rerun, the menu will stay expanded and a collapse button will be displayed. The parameter is only used when ``position="sidebar"``. Returns ------- StreamlitPage The current page selected by the user. To run the page, you must use the ``.run()`` method on it. Examples -------- The following examples show different possible entrypoint files, each named ``streamlit_app.py``. An entrypoint file is passed to ``streamlit run``. It manages your app's navigation and serves as a router between pages. **Example 1: Use a callable or Python file as a page** You can declare pages from callables or file paths. If you pass callables or paths to ``st.navigation`` as a page-like objects, they are internally converted to ``StreamlitPage`` objects using ``st.Page``. In this case, the page titles, icons, and paths are inferred from the file or callable names. ``page_1.py`` (in the same directory as your entrypoint file): >>> import streamlit as st >>> >>> st.title("Page 1") ``streamlit_app.py``: >>> import streamlit as st >>> >>> def page_2(): ... st.title("Page 2") >>> >>> pg = st.navigation(["page_1.py", page_2]) >>> pg.run() .. output:: https://doc-navigation-example-1.streamlit.app/ height: 200px **Example 2: Group pages into sections and customize them with ``st.Page``** You can use a dictionary to create sections within your navigation menu. In the following example, each page is similar to Page 1 in Example 1, and all pages are in the same directory. However, you can use Python files from anywhere in your repository. ``st.Page`` is used to give each page a custom title. For more information, see |st.Page|_. Directory structure: >>> your_repository/ >>> ├── create_account.py >>> ├── learn.py >>> ├── manage_account.py >>> ├── streamlit_app.py >>> └── trial.py ``streamlit_app.py``: >>> import streamlit as st >>> >>> pages = { ... "Your account": [ ... st.Page("create_account.py", title="Create your account"), ... st.Page("manage_account.py", title="Manage your account"), ... ], ... "Resources": [ ... st.Page("learn.py", title="Learn about us"), ... st.Page("trial.py", title="Try it out"), ... ], ... } >>> >>> pg = st.navigation(pages) >>> pg.run() .. output:: https://doc-navigation-example-2.streamlit.app/ height: 300px **Example 3: Use top navigation** You can use the ``position`` parameter to place the navigation at the top of the app. This is useful for apps with a lot of pages because it allows you to create collapsible sections for each group of pages. The following example uses the same directory structure as Example 2 and shows how to create a top navigation menu. ``streamlit_app.py``: >>> import streamlit as st >>> >>> pages = { ... "Your account": [ ... st.Page("create_account.py", title="Create your account"), ... st.Page("manage_account.py", title="Manage your account"), ... ], ... "Resources": [ ... st.Page("learn.py", title="Learn about us"), ... st.Page("trial.py", title="Try it out"), ... ], ... } >>> >>> pg = st.navigation(pages, position="top") >>> pg.run() .. output:: https://doc-navigation-top.streamlit.app/ height: 300px **Example 4: Stateful widgets across multiple pages** Call widget functions in your entrypoint file when you want a widget to be stateful across pages. Assign keys to your common widgets and access their values through Session State within your pages. ``streamlit_app.py``: >>> import streamlit as st >>> >>> def page1(): >>> st.write(st.session_state.foo) >>> >>> def page2(): >>> st.write(st.session_state.bar) >>> >>> # Widgets shared by all the pages >>> st.sidebar.selectbox("Foo", ["A", "B", "C"], key="foo") >>> st.sidebar.checkbox("Bar", key="bar") >>> >>> pg = st.navigation([page1, page2]) >>> pg.run() .. output:: https://doc-navigation-multipage-widgets.streamlit.app/ height: 350px .. |st.Page| replace:: ``st.Page`` .. _st.Page: https://docs.streamlit.io/develop/api-reference/navigation/st.page """ # Validate position parameter if not isinstance(position, str) or position not in ["sidebar", "hidden", "top"]: raise StreamlitAPIException( f'Invalid position "{position}". ' 'The position parameter must be one of "sidebar", "hidden", or "top".' ) # Disable the use of the pages feature (ie disregard v1 behavior of Multipage Apps) PagesManager.uses_pages_directory = False return _navigation(pages, position=position, expanded=expanded) def _navigation( pages: Sequence[PageType] | Mapping[SectionHeader, Sequence[PageType]], *, position: Literal["sidebar", "hidden", "top"], expanded: bool, ) -> StreamlitPage: if isinstance(pages, Sequence): converted_pages = [convert_to_streamlit_page(p) for p in pages] nav_sections = {"": converted_pages} else: nav_sections = { section: [convert_to_streamlit_page(p) for p in section_pages] for section, section_pages in pages.items() } page_list = pages_from_nav_sections(nav_sections) if not page_list: raise StreamlitAPIException( "`st.navigation` must be called with at least one `st.Page`." ) default_page = None pagehash_to_pageinfo: dict[PageHash, PageInfo] = {} # Get the default page. for section_header in nav_sections: for page in nav_sections[section_header]: if page._default: if default_page is not None: raise StreamlitAPIException( "Multiple Pages specified with `default=True`. " "At most one Page can be set to default." ) default_page = page if default_page is None: default_page = page_list[0] default_page._default = True ctx = get_script_run_ctx() if not ctx: # This should never run in Streamlit, but we want to make sure that # the function always returns a page default_page._can_be_called = True return default_page # Build the pagehash-to-pageinfo mapping. for section_header in nav_sections: for page in nav_sections[section_header]: script_path = str(page._page) if isinstance(page._page, Path) else "" script_hash = page._script_hash if script_hash in pagehash_to_pageinfo: # The page script hash is solely based on the url path # So duplicate page script hashes are due to duplicate url paths raise StreamlitAPIException( f"Multiple Pages specified with URL pathname {page.url_path}. " "URL pathnames must be unique. The url pathname may be " "inferred from the filename, callable name, or title." ) pagehash_to_pageinfo[script_hash] = { "page_script_hash": script_hash, "page_name": page.title, "icon": page.icon, "script_path": script_path, "url_pathname": page.url_path, } msg = ForwardMsg() # Handle position logic correctly if position == "hidden": msg.navigation.position = NavigationProto.Position.HIDDEN elif position == "top": msg.navigation.position = NavigationProto.Position.TOP elif position == "sidebar": # Only apply config override if position is sidebar if config.get_option("client.showSidebarNavigation") is False: msg.navigation.position = NavigationProto.Position.HIDDEN else: msg.navigation.position = NavigationProto.Position.SIDEBAR msg.navigation.expanded = expanded msg.navigation.sections[:] = nav_sections.keys() for section_header in nav_sections: for page in nav_sections[section_header]: p = msg.navigation.app_pages.add() p.page_script_hash = page._script_hash p.page_name = page.title p.icon = f"emoji:{page.icon}" if is_emoji(page.icon) else page.icon p.is_default = page._default p.section_header = section_header p.url_pathname = page.url_path # Inform our page manager about the set of pages we have ctx.pages_manager.set_pages(pagehash_to_pageinfo) found_page = ctx.pages_manager.get_page_script( fallback_page_hash=default_page._script_hash ) page_to_return = None if found_page: found_page_script_hash = found_page["page_script_hash"] matching_pages = [ p for p in page_list if p._script_hash == found_page_script_hash ] if len(matching_pages) > 0: page_to_return = matching_pages[0] if not page_to_return: send_page_not_found(ctx) page_to_return = default_page # Ordain the page that can be called page_to_return._can_be_called = True msg.navigation.page_script_hash = page_to_return._script_hash # Set the current page script hash to the page that is going to be executed ctx.set_mpa_v2_page(page_to_return._script_hash) # This will either navigation or yield if the page is not found ctx.enqueue(msg) return page_to_return
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/echo.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import ast import contextlib import re import textwrap import traceback from typing import TYPE_CHECKING, Any, Literal, cast from streamlit.runtime.metrics_util import gather_metrics if TYPE_CHECKING: from collections.abc import Generator, Iterable _SPACES_RE = re.compile("\\s*") _EMPTY_LINE_RE = re.compile("\\s*\n") @gather_metrics("echo") @contextlib.contextmanager def echo( code_location: Literal["above", "below"] = "above", ) -> Generator[None, None, None]: """Use in a `with` block to draw some code on the app, then execute it. Parameters ---------- code_location : "above" or "below" Whether to show the echoed code before or after the results of the executed code block. Example ------- >>> import streamlit as st >>> >>> with st.echo(): >>> st.write('This code will be printed') """ from streamlit import code, empty, source_util, warning if code_location == "below": show_code = code show_warning = warning else: placeholder = empty() show_code = placeholder.code show_warning = placeholder.warning try: # Get stack frame *before* running the echoed code. The frame's # line number will point to the `st.echo` statement we're running. frame = traceback.extract_stack()[-3] filename, start_line = frame.filename, frame.lineno or 0 # Read the file containing the source code of the echoed statement. with source_util.open_python_file(filename) as source_file: source_lines = source_file.readlines() # Use ast to parse the Python file and find the code block to display root_node = ast.parse("".join(source_lines)) line_to_node_map: dict[int, Any] = {} def collect_body_statements(node: ast.AST) -> None: if not hasattr(node, "body"): return for child in ast.iter_child_nodes(node): # If child doesn't have "lineno", it is not something we could display if hasattr(child, "lineno"): line_to_node_map[cast("int", child.lineno)] = child collect_body_statements(child) collect_body_statements(root_node) # In AST module the lineno (line numbers) are 1-indexed, # so we decrease it by 1 to lookup in source lines list echo_block_start_line = line_to_node_map[start_line].body[0].lineno - 1 echo_block_end_line = line_to_node_map[start_line].end_lineno lines_to_display = source_lines[echo_block_start_line:echo_block_end_line] code_string = textwrap.dedent("".join(lines_to_display)) # Run the echoed code... yield # And draw the code string to the app! show_code(code_string, "python") except FileNotFoundError as err: show_warning(f"Unable to display code. {err}") def _get_initial_indent(lines: Iterable[str]) -> int: """Return the indent of the first non-empty line in the list. If all lines are empty, return 0. """ for line in lines: indent = _get_indent(line) if indent is not None: return indent return 0 def _get_indent(line: str) -> int | None: """Get the number of whitespaces at the beginning of the given line. If the line is empty, or if it contains just whitespace and a newline, return None. """ if _EMPTY_LINE_RE.match(line) is not None: return None match = _SPACES_RE.match(line) return match.end() if match is not None else 0
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/logo.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Handle App logos.""" from __future__ import annotations from typing import Literal from streamlit import url_util from streamlit.elements.lib.image_utils import AtomicImage, image_to_url from streamlit.elements.lib.layout_utils import LayoutConfig from streamlit.errors import StreamlitAPIException from streamlit.proto.ForwardMsg_pb2 import ForwardMsg from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx def _invalid_logo_text(field_name: str) -> str: return ( f"The {field_name} passed to st.logo is invalid - See " "[documentation](https://docs.streamlit.io/develop/api-reference/media/st.logo) " "for more information on valid types" ) @gather_metrics("logo") def logo( image: AtomicImage, *, # keyword-only args: size: Literal["small", "medium", "large"] = "medium", link: str | None = None, icon_image: AtomicImage | None = None, ) -> None: r""" Renders a logo in the upper-left corner of your app and its sidebar. If ``st.logo`` is called multiple times within a page, Streamlit will render the image passed in the last call. For the most consistent results, call ``st.logo`` early in your page script and choose an image that works well in both light and dark mode. Avoid empty margins around your image. If your logo does not work well for both light and dark mode, consider setting the theme and hiding the settings menu from users with the `configuration option <https://docs.streamlit.io/develop/api-reference/configuration/config.toml>`_ ``client.toolbarMode="minimal"``. Parameters ---------- image: Anything supported by st.image (except list) The image to display in the upper-left corner of your app and its sidebar. This can be any of the types supported by |st.image|_ except a list. If ``icon_image`` is also provided, then Streamlit will only display ``image`` in the sidebar. Streamlit scales the image to a max height set by ``size`` and a max width to fit within the sidebar. .. |st.image| replace:: ``st.image`` .. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image size: "small", "medium", or "large" The size of the image displayed in the upper-left corner of the app and its sidebar. The possible values are as follows: - ``"small"``: 20px max height - ``"medium"`` (default): 24px max height - ``"large"``: 32px max height link : str or None The external URL to open when a user clicks on the logo. The URL must start with "\http://" or "\https://". If ``link`` is ``None`` (default), the logo will not include a hyperlink. icon_image: Anything supported by st.image (except list) or None An optional, typically smaller image to replace ``image`` in the upper-left corner when the sidebar is closed. This can be any of the types supported by ``st.image`` except a list. If ``icon_image`` is ``None`` (default), Streamlit will always display ``image`` in the upper-left corner, regardless of whether the sidebar is open or closed. Otherwise, Streamlit will render ``icon_image`` in the upper-left corner of the app when the sidebar is closed. Streamlit scales the image to a max height set by ``size`` and a max width to fit within the sidebar. If the sidebar is closed, the max width is retained from when it was last open. For best results, pass a wide or horizontal image to ``image`` and a square image to ``icon_image``. Or, pass a square image to ``image`` and leave ``icon_image=None``. Examples -------- A common design practice is to use a wider logo in the sidebar, and a smaller, icon-styled logo in your app's main body. >>> import streamlit as st >>> >>> st.logo( ... LOGO_URL_LARGE, ... link="https://streamlit.io/gallery", ... icon_image=LOGO_URL_SMALL, ... ) Try switching logos around in the following example: >>> import streamlit as st >>> >>> HORIZONTAL_RED = "images/horizontal_red.png" >>> ICON_RED = "images/icon_red.png" >>> HORIZONTAL_BLUE = "images/horizontal_blue.png" >>> ICON_BLUE = "images/icon_blue.png" >>> >>> options = [HORIZONTAL_RED, ICON_RED, HORIZONTAL_BLUE, ICON_BLUE] >>> sidebar_logo = st.selectbox("Sidebar logo", options, 0) >>> main_body_logo = st.selectbox("Main body logo", options, 1) >>> >>> st.logo(sidebar_logo, icon_image=main_body_logo) >>> st.sidebar.markdown("Hi!") .. output:: https://doc-logo.streamlit.app/ height: 300px """ ctx = get_script_run_ctx() if ctx is None: return fwd_msg = ForwardMsg() try: image_url = image_to_url( image, layout_config=LayoutConfig(width="content"), clamp=False, channels="RGB", output_format="auto", image_id="logo", ) fwd_msg.logo.image = image_url except Exception as ex: raise StreamlitAPIException(_invalid_logo_text("image")) from ex if link: # Handle external links: if url_util.is_url(link, ("http", "https")): fwd_msg.logo.link = link else: raise StreamlitAPIException( f"Invalid link: {link} - the link param supports external links only and must " f"start with either http:// or https://." ) if icon_image: try: icon_image_url = image_to_url( icon_image, layout_config=LayoutConfig(width="content"), clamp=False, channels="RGB", output_format="auto", image_id="icon-image", ) fwd_msg.logo.icon_image = icon_image_url except Exception as ex: raise StreamlitAPIException(_invalid_logo_text("icon_image")) from ex def validate_size(size: str) -> str: if isinstance(size, str): image_size = size.lower() valid_sizes = ["small", "medium", "large"] if image_size in valid_sizes: return image_size raise StreamlitAPIException( f'The size argument to st.logo must be "small", "medium", or "large". \n' f"The argument passed was {size}." ) fwd_msg.logo.size = validate_size(size) ctx.enqueue(fwd_msg)
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/commands/page_config.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import random from collections.abc import Mapping from pathlib import Path from textwrap import dedent from typing import TYPE_CHECKING, Any, Final, Literal, TypeAlias, cast from streamlit.elements.lib.image_utils import AtomicImage, image_to_url from streamlit.elements.lib.layout_utils import LayoutConfig from streamlit.errors import ( StreamlitInvalidMenuItemKeyError, StreamlitInvalidPageLayoutError, StreamlitInvalidSidebarStateError, StreamlitInvalidURLError, ) from streamlit.proto.ForwardMsg_pb2 import ForwardMsg as ForwardProto from streamlit.proto.PageConfig_pb2 import PageConfig as PageConfigProto from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx from streamlit.string_util import is_emoji, validate_material_icon from streamlit.url_util import is_url if TYPE_CHECKING: from typing import TypeGuard GET_HELP_KEY: Final = "get help" REPORT_A_BUG_KEY: Final = "report a bug" ABOUT_KEY: Final = "about" PageIcon: TypeAlias = AtomicImage | str Layout: TypeAlias = Literal["centered", "wide"] InitialSideBarState: TypeAlias = Literal["auto", "expanded", "collapsed"] | int _GetHelp: TypeAlias = Literal["Get help", "Get Help", "get help"] _ReportABug: TypeAlias = Literal["Report a bug", "report a bug"] _About: TypeAlias = Literal["About", "about"] MenuKey: TypeAlias = Literal[_GetHelp, _ReportABug, _About] MenuItems: TypeAlias = Mapping[MenuKey, str | None] RANDOM_EMOJIS: Final = list( "🔥™🎉🚀🌌💣✨🌙🎆🎇💥🤩🤙🌛🤘⬆💡🤪🥂⚡💨🌠🎊🍿😛🔮🤟🌃🍃🍾💫▪🌴🎈🎬🌀🎄😝☔⛽🍂💃😎🍸🎨🥳☀😍🅱🌞😻🌟😜💦💅🦄😋😉👻🍁🤤👯🌻‼🌈👌🎃💛😚🔫🙌👽🍬🌅☁🍷👭☕🌚💁👅🥰🍜😌🎥🕺❕🧡☄💕🍻✅🌸🚬🤓🍹®☺💪😙☘🤠✊🤗🍵🤞😂💯😏📻🎂💗💜🌊❣🌝😘💆🤑🌿🦋😈⛄🚿😊🌹🥴😽💋😭🖤🙆👐⚪💟☃🙈🍭💻🥀🚗🤧🍝💎💓🤝💄💖🔞⁉⏰🕊🎧☠♥🌳🏾🙉⭐💊🍳🌎🙊💸❤🔪😆🌾✈📚💀🏠✌🏃🌵🚨💂🤫🤭😗😄🍒👏🙃🖖💞😅🎅🍄🆓👉💩🔊🤷⌚👸😇🚮💏👳🏽💘💿💉👠🎼🎶🎤👗❄🔐🎵🤒🍰👓🏄🌲🎮🙂📈🚙📍😵🗣❗🌺🙄👄🚘🥺🌍🏡♦💍🌱👑👙☑👾🍩🥶📣🏼🤣☯👵🍫➡🎀😃✋🍞🙇😹🙏👼🐝⚫🎁🍪🔨🌼👆👀😳🌏📖👃🎸👧💇🔒💙😞⛅🏻🍴😼🗿🍗♠🦁✔🤖☮🐢🐎💤😀🍺😁😴📺☹😲👍🎭💚🍆🍋🔵🏁🔴🔔🧐👰☎🏆🤡🐠📲🙋📌🐬✍🔑📱💰🐱💧🎓🍕👟🐣👫🍑😸🍦👁🆗🎯📢🚶🦅🐧💢🏀🚫💑🐟🌽🏊🍟💝💲🐍🍥🐸☝♣👊⚓❌🐯🏈📰🌧👿🐳💷🐺📞🆒🍀🤐🚲🍔👹🙍🌷🙎🐥💵🔝📸⚠❓🎩✂🍼😑⬇⚾🍎💔🐔⚽💭🏌🐷🍍✖🍇📝🍊🐙👋🤔🥊🗽🐑🐘🐰💐🐴♀🐦🍓✏👂🏴👇🆘😡🏉👩💌😺✝🐼🐒🐶👺🖕👬🍉🐻🐾⬅⏬▶👮🍌♂🔸👶🐮👪⛳🐐🎾🐕👴🐨🐊🔹©🎣👦👣👨👈💬⭕📹📷" ) def _lower_clean_dict_keys(dict: MenuItems) -> dict[str, Any]: return {str(k).lower().strip(): v for k, v in dict.items()} def _get_favicon_string(page_icon: PageIcon) -> str: """Return the string to pass to the frontend to have it show the given PageIcon. If page_icon is a string that looks like an emoji (or an emoji shortcode), we return it as-is. Otherwise we use `image_to_url` to return a URL. (If `image_to_url` raises an error and page_icon is a string, return the unmodified page_icon string instead of re-raising the error.) """ # Choose a random emoji. if page_icon == "random": return get_random_emoji() # If page_icon is an emoji, return it as is. if isinstance(page_icon, str) and is_emoji(page_icon): return f"emoji:{page_icon}" if isinstance(page_icon, str) and page_icon.startswith(":material"): return validate_material_icon(page_icon) # Convert Path to string if necessary if isinstance(page_icon, Path): page_icon = str(page_icon) # Fall back to image_to_url. try: return image_to_url( page_icon, layout_config=LayoutConfig( width="stretch" ), # Always use full width for favicons clamp=False, channels="RGB", output_format="auto", image_id="favicon", ) except Exception: if isinstance(page_icon, str): # This fall-thru handles emoji shortcode strings (e.g. ":shark:"), # which aren't valid filenames and so will cause an Exception from # `image_to_url`. return page_icon raise @gather_metrics("set_page_config") def set_page_config( page_title: str | None = None, page_icon: PageIcon | None = None, layout: Layout | None = None, initial_sidebar_state: InitialSideBarState | None = None, menu_items: MenuItems | None = None, ) -> None: """ Configure the default settings of the page. This command can be called multiple times in a script run to dynamically change the page configuration. The calls are additive, with each successive call overriding only the parameters that are specified. Parameters ---------- page_title: str or None The page title, shown in the browser tab. If this is ``None`` (default), the page title is inherited from the previous call of ``st.set_page_config``. If this is ``None`` and no previous call exists, the page title is inferred from the page source. If a page source is a Python file, its inferred title is derived from the filename. If a page source is a callable object, its inferred title is derived from the callable's name. page_icon : Anything supported by st.image (except list), str, or None The page favicon. If ``page_icon`` is ``None`` (default), the page icon is inherited from the previous call of ``st.set_page_config``. If this is ``None`` and no previous call exists, the favicon is a monochrome Streamlit logo. In addition to the types supported by |st.image|_ (except list), the following strings are valid: - A single-character emoji. For example, you can set ``page_icon="🦈"``. - An emoji short code. For example, you can set ``page_icon=":shark:"``. For a list of all supported codes, see https://share.streamlit.io/streamlit/emoji-shortcodes. - The string literal, ``"random"``. You can set ``page_icon="random"`` to set a random emoji from the supported list above. - An icon from the Material Symbols library (rounded style) in the format ``":material/icon_name:"`` where "icon_name" is the name of the icon in snake case. For example, ``page_icon=":material/thumb_up:"`` will display the Thumb Up icon. Find additional icons in the `Material Symbols \ <https://fonts.google.com/icons?icon.set=Material+Symbols&icon.style=Rounded>`_ font library. .. note:: Colors are not supported for Material icons. When you use a Material icon for favicon, it will be black, regardless of browser theme. .. |st.image| replace:: ``st.image`` .. _st.image: https://docs.streamlit.io/develop/api-reference/media/st.image layout: "centered", "wide", or None How the page content should be laid out. If this is ``None`` (default), the page layout is inherited from the previous call of ``st.set_page_config``. If this is ``None`` and no previous call exists, the page layout is ``"centered"``. ``"centered"`` constrains the elements into a centered column of fixed width. ``"wide"`` uses the entire screen. initial_sidebar_state: "auto", "expanded", "collapsed", int, or None How the sidebar should start out. If this is ``None`` (default), the sidebar state is inherited from the previous call of ``st.set_page_config``. If no previous call exists, the sidebar state is ``"auto"``. The following states are supported: - ``"auto"``: The sidebar is hidden on small devices and shown otherwise. - ``"expanded"``: The sidebar is shown initially. - ``"collapsed"``: The sidebar is hidden initially. - ``int``: Set the initial sidebar width in pixels. The sidebar will use "auto" behavior but start with the specified width. Must be a positive integer. The width is limited to a minimum of 200px and a maximum of 600px. In most cases, ``"auto"`` provides the best user experience across devices of different sizes. menu_items: dict Configure the menu that appears on the top-right side of this app. The keys in this dict denote the menu item to configure. The following keys can have string or ``None`` values: - "Get help": The URL this menu item should point to. - "Report a Bug": The URL this menu item should point to. - "About": A markdown string to show in the About dialog. A URL may also refer to an email address e.g. ``mailto:john@example.com``. If you do not include a key, its menu item will be hidden (unless it was set by a previous call to ``st.set_page_config``). To remove an item that was specified in a previous call to ``st.set_page_config``, set its value to ``None`` in the dictionary. Example ------- >>> import streamlit as st >>> >>> st.set_page_config( ... page_title="Ex-stream-ly Cool App", ... page_icon="🧊", ... layout="wide", ... initial_sidebar_state="expanded", ... menu_items={ ... 'Get Help': 'https://www.extremelycoolapp.com/help', ... 'Report a bug': "https://www.extremelycoolapp.com/bug", ... 'About': "# This is a header. This is an *extremely* cool app!" ... } ... ) """ msg = ForwardProto() if page_title is not None: msg.page_config_changed.title = page_title if page_icon is not None: msg.page_config_changed.favicon = _get_favicon_string(page_icon) pb_layout: PageConfigProto.Layout.ValueType if layout == "centered": pb_layout = PageConfigProto.CENTERED elif layout == "wide": pb_layout = PageConfigProto.WIDE elif layout is None: # Allows for multiple (additive) calls to set_page_config pb_layout = PageConfigProto.LAYOUT_UNSET else: # Note: Pylance incorrectly notes this error as unreachable raise StreamlitInvalidPageLayoutError(layout=layout) msg.page_config_changed.layout = pb_layout pb_sidebar_state: PageConfigProto.SidebarState.ValueType if initial_sidebar_state == "auto": pb_sidebar_state = PageConfigProto.AUTO elif initial_sidebar_state == "expanded": pb_sidebar_state = PageConfigProto.EXPANDED elif initial_sidebar_state == "collapsed": pb_sidebar_state = PageConfigProto.COLLAPSED elif initial_sidebar_state is None: # Allows for multiple (additive) calls to set_page_config pb_sidebar_state = PageConfigProto.SIDEBAR_UNSET elif isinstance(initial_sidebar_state, int): # Integer values set the sidebar width and use AUTO state if initial_sidebar_state <= 0: raise StreamlitInvalidSidebarStateError( initial_sidebar_state=f"width must be positive (got {initial_sidebar_state})" ) pb_sidebar_state = PageConfigProto.AUTO msg.page_config_changed.initial_sidebar_width.pixel_width = ( initial_sidebar_state ) else: # Note: Pylance incorrectly notes this error as unreachable raise StreamlitInvalidSidebarStateError( initial_sidebar_state=initial_sidebar_state ) msg.page_config_changed.initial_sidebar_state = pb_sidebar_state if menu_items is not None: lowercase_menu_items = cast("MenuItems", _lower_clean_dict_keys(menu_items)) validate_menu_items(lowercase_menu_items) menu_items_proto = msg.page_config_changed.menu_items set_menu_items_proto(lowercase_menu_items, menu_items_proto) ctx = get_script_run_ctx() if ctx is None: return ctx.enqueue(msg) def get_random_emoji() -> str: # TODO: fix the random seed with a hash of the user's app code, for stability? return random.choice(RANDOM_EMOJIS) # noqa: S311 def set_menu_items_proto( lowercase_menu_items: MenuItems, menu_items_proto: PageConfigProto.MenuItems ) -> None: if GET_HELP_KEY in lowercase_menu_items: if lowercase_menu_items[GET_HELP_KEY] is not None: menu_items_proto.get_help_url = lowercase_menu_items[GET_HELP_KEY] else: menu_items_proto.hide_get_help = True if REPORT_A_BUG_KEY in lowercase_menu_items: if lowercase_menu_items[REPORT_A_BUG_KEY] is not None: menu_items_proto.report_a_bug_url = lowercase_menu_items[REPORT_A_BUG_KEY] else: menu_items_proto.hide_report_a_bug = True if ABOUT_KEY in lowercase_menu_items: if lowercase_menu_items[ABOUT_KEY] is not None: menu_items_proto.about_section_md = dedent( lowercase_menu_items[ABOUT_KEY] or "" ) else: # For multiple calls to set_page_config, clears previously set about markdown menu_items_proto.clear_about_md = True def validate_menu_items(menu_items: MenuItems) -> None: for k, v in menu_items.items(): if not valid_menu_item_key(k): raise StreamlitInvalidMenuItemKeyError(key=k) if v is not None and ( not is_url(v, ("http", "https", "mailto")) and k != ABOUT_KEY ): raise StreamlitInvalidURLError(url=v) def valid_menu_item_key(key: str) -> TypeGuard[MenuKey]: return key in {GET_HELP_KEY, REPORT_A_BUG_KEY, ABOUT_KEY}
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/web/__init__.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/web/cache_storage_manager_config.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING from streamlit.runtime.caching.storage.local_disk_cache_storage import ( LocalDiskCacheStorageManager, ) if TYPE_CHECKING: from streamlit.runtime.caching.storage import CacheStorageManager def create_default_cache_storage_manager() -> CacheStorageManager: """ Get the cache storage manager. It would be used both in server.py and in cli.py to have unified cache storage. Returns ------- CacheStorageManager The cache storage manager. """ return LocalDiskCacheStorageManager()
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/web/bootstrap.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import asyncio import os import signal import sys from typing import Any, Final from streamlit import cli_util, config, env_util, file_util, net_util, secrets from streamlit.logger import get_logger from streamlit.watcher import report_watchdog_availability, watch_file from streamlit.web.server import Server, server_address_is_unix_socket, server_util _LOGGER: Final = get_logger(__name__) # The maximum possible total size of a static directory. # We agreed on these limitations for the initial release of static file sharing, # based on security concerns from the SiS and Community Cloud teams MAX_APP_STATIC_FOLDER_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB def _set_up_signal_handler(server: Server) -> None: _LOGGER.debug("Setting up signal handler") def signal_handler(signal_number: int, stack_frame: Any) -> None: # noqa: ARG001 # The server will shut down its threads and exit its loop. server.stop() signal.signal(signal.SIGTERM, signal_handler) signal.signal(signal.SIGINT, signal_handler) if sys.platform == "win32": signal.signal(signal.SIGBREAK, signal_handler) else: signal.signal(signal.SIGQUIT, signal_handler) def _fix_sys_path(main_script_path: str) -> None: """Add the script's folder to the sys path. Python normally does this automatically, but since we exec the script ourselves we need to do it instead. """ sys.path.insert(0, os.path.dirname(main_script_path)) def _maybe_install_uvloop(running_in_event_loop: bool) -> None: """Install uvloop as the default event loop policy if available.""" if running_in_event_loop: return if env_util.IS_WINDOWS: return try: import uvloop except ModuleNotFoundError: return try: uvloop.install() _LOGGER.debug("uvloop installed as default event loop policy.") except Exception: _LOGGER.warning( "Failed to install uvloop. Falling back to default loop.", exc_info=True ) def _fix_tornado_crash() -> None: """Set default asyncio policy to be compatible with Tornado 6. Tornado 6 (at least) is not compatible with the default asyncio implementation on Windows. So here we pick the older SelectorEventLoopPolicy when the OS is Windows if the known-incompatible default policy is in use. This has to happen as early as possible to make it a low priority and overridable See: https://github.com/tornadoweb/tornado/issues/2608 FIXME: if/when tornado supports the defaults in asyncio, remove and bump tornado requirement for py38 """ if env_util.IS_WINDOWS: try: from asyncio import ( # type: ignore[attr-defined] WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy, ) except ImportError: pass # Not affected else: if type(asyncio.get_event_loop_policy()) is WindowsProactorEventLoopPolicy: # WindowsProactorEventLoopPolicy is not compatible with # Tornado 6 fallback to the pre-3.8 default of Selector asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy()) def _fix_sys_argv(main_script_path: str, args: list[str]) -> None: """sys.argv needs to exclude streamlit arguments and parameters and be set to what a user's script may expect. """ import sys sys.argv = [main_script_path, *list(args)] def _on_server_start(server: Server) -> None: _maybe_print_static_folder_warning(server.main_script_path) _print_url(server.is_running_hello) report_watchdog_availability() # Load secrets.toml if it exists. If the file doesn't exist, this # function will return without raising an exception. We catch any parse # errors and display them here. try: secrets.load_if_toml_exists() except Exception: _LOGGER.exception("Failed to load secrets.toml file") def maybe_open_browser() -> None: if config.get_option("server.headless"): # Don't open browser when in headless mode. return if config.is_manually_set("browser.serverAddress"): addr = config.get_option("browser.serverAddress") elif config.is_manually_set("server.address"): if server_address_is_unix_socket(): # Don't open browser when server address is an unix socket return addr = config.get_option("server.address") else: addr = "localhost" cli_util.open_browser(server_util.get_url(addr)) # Schedule the browser to open on the main thread. asyncio.get_running_loop().call_soon(maybe_open_browser) def _fix_pydeck_mapbox_api_warning() -> None: """Sets MAPBOX_API_KEY environment variable needed for PyDeck otherwise it will throw an exception. """ if "MAPBOX_API_KEY" not in os.environ: os.environ["MAPBOX_API_KEY"] = config.get_option("mapbox.token") def _maybe_print_static_folder_warning(main_script_path: str) -> None: """Prints a warning if the static folder is misconfigured.""" if config.get_option("server.enableStaticServing"): static_folder_path = file_util.get_app_static_dir(main_script_path) if not os.path.isdir(static_folder_path): cli_util.print_to_cli( f"WARNING: Static file serving is enabled, but no static folder found " f"at {static_folder_path}. To disable static file serving, " f"set server.enableStaticServing to false.", fg="yellow", ) else: # Raise warning when static folder size is larger than 1 GB static_folder_size = file_util.get_directory_size(static_folder_path) if static_folder_size > MAX_APP_STATIC_FOLDER_SIZE: config.set_option("server.enableStaticServing", False) cli_util.print_to_cli( "WARNING: Static folder size is larger than 1GB. " "Static file serving has been disabled.", fg="yellow", ) def _print_url(is_running_hello: bool) -> None: if is_running_hello: title_message = "Welcome to Streamlit. Check out our demo in your browser." else: title_message = "You can now view your Streamlit app in your browser." named_urls = [] if config.is_manually_set("browser.serverAddress"): named_urls = [ ("URL", server_util.get_url(config.get_option("browser.serverAddress"))) ] elif ( config.is_manually_set("server.address") and not server_address_is_unix_socket() ): named_urls = [ ("URL", server_util.get_url(config.get_option("server.address"))), ] elif server_address_is_unix_socket(): named_urls = [ ("Unix Socket", config.get_option("server.address")), ] else: named_urls = [ ("Local URL", server_util.get_url("localhost")), ] internal_ip = net_util.get_internal_ip() if internal_ip: named_urls.append(("Network URL", server_util.get_url(internal_ip))) if config.get_option("server.headless"): external_ip = net_util.get_external_ip() if external_ip: named_urls.append(("External URL", server_util.get_url(external_ip))) cli_util.print_to_cli("") cli_util.print_to_cli(f" {title_message}", fg="blue", bold=True) cli_util.print_to_cli("") for url_name, url in named_urls: cli_util.print_to_cli(f" {url_name}: ", nl=False, fg="blue") cli_util.print_to_cli(url, bold=True) cli_util.print_to_cli("") if is_running_hello: cli_util.print_to_cli(" Ready to create your own Python apps super quickly?") cli_util.print_to_cli(" Head over to ", nl=False) cli_util.print_to_cli("https://docs.streamlit.io", bold=True) cli_util.print_to_cli("") cli_util.print_to_cli(" May you create awesome apps!") cli_util.print_to_cli("") cli_util.print_to_cli("") def load_config_options(flag_options: dict[str, Any]) -> None: """Load config options from config.toml files, then overlay the ones set by flag_options. The "streamlit run" command supports passing Streamlit's config options as flags. This function reads through the config options set via flag, massages them, and passes them to get_config_options() so that they overwrite config option defaults and those loaded from config.toml files. Parameters ---------- flag_options : dict[str, Any] A dict of config options where the keys are the CLI flag version of the config option names. """ # We want to filter out two things: values that are None, and values that # are empty tuples. The latter is a special case that indicates that the # no values were provided, and the config should reset to the default options_from_flags = { name.replace("_", "."): val for name, val in flag_options.items() if val is not None and val != () } # Force a reparse of config files (if they exist). The result is cached # for future calls. config.get_config_options(force_reparse=True, options_from_flags=options_from_flags) def _install_config_watchers(flag_options: dict[str, Any]) -> None: def on_config_changed(_path: str) -> None: load_config_options(flag_options) for filename in config.get_config_files("config.toml"): if os.path.exists(filename): watch_file(filename, on_config_changed) def run( main_script_path: str, is_hello: bool, args: list[str], flag_options: dict[str, Any], *, stop_immediately_for_testing: bool = False, ) -> None: """Run a script in a separate thread and start a server for the app. This starts a blocking asyncio eventloop. """ _fix_sys_path(main_script_path) _fix_tornado_crash() _fix_sys_argv(main_script_path, args) _fix_pydeck_mapbox_api_warning() _install_config_watchers(flag_options) # Create the server. It won't start running yet. server = Server(main_script_path, is_hello) async def run_server() -> None: # Start the server await server.start() _on_server_start(server) # Install a signal handler that will shut down the server # and close all our threads _set_up_signal_handler(server) # return immediately if we're testing the server start if stop_immediately_for_testing: _LOGGER.debug("Stopping server immediately for testing") server.stop() # Wait until `Server.stop` is called, either by our signal handler, or # by a debug websocket session. await server.stopped # Define a main function to handle the event loop logic async def main() -> None: await run_server() # Handle running in existing event loop vs creating new one running_in_event_loop = False try: # Check if we're already in an event loop asyncio.get_running_loop() running_in_event_loop = True except RuntimeError: # No running event loop - this is expected for normal CLI usage pass if running_in_event_loop: _LOGGER.debug("Running server in existing event loop.") # We're in an existing event loop. task = asyncio.create_task(main(), name="bootstrap.run_server") # Store task reference on the server to keep it alive # This prevents the task from being garbage collected server._bootstrap_task = task else: _maybe_install_uvloop(running_in_event_loop) # No running event loop, so we can use asyncio.run # This is the normal case when running streamlit from the command line _LOGGER.debug("Starting new event loop for server") asyncio.run(main())
0
hf_public_repos/streamlit/lib/streamlit
hf_public_repos/streamlit/lib/streamlit/web/cli.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """A script which is run when the Streamlit package is executed.""" from __future__ import annotations import os import sys from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING, Any, Final, TypeVar # We cannot lazy-load click here because its used via decorators. import click from streamlit import config as _config from streamlit.runtime import caching from streamlit.runtime.credentials import Credentials, check_credentials from streamlit.web import bootstrap from streamlit.web.cache_storage_manager_config import ( create_default_cache_storage_manager, ) if TYPE_CHECKING: from streamlit.config_option import ConfigOption ACCEPTED_FILE_EXTENSIONS: Final = ("py", "py3") LOG_LEVELS: Final = ("error", "warning", "info", "debug") def _convert_config_option_to_click_option( config_option: ConfigOption, ) -> dict[str, Any]: """Composes given config option options as options for click lib.""" option = f"--{config_option.key}" param = config_option.key.replace(".", "_") description = config_option.description if config_option.deprecated: if description is None: description = "" description += ( f"\n {config_option.deprecation_text} - {config_option.expiration_date}" ) return { "param": param, "description": description, "type": config_option.type, "option": option, "envvar": config_option.env_var, "multiple": config_option.multiple, } def _make_sensitive_option_callback( config_option: ConfigOption, ) -> Callable[[click.Context, click.Parameter, Any], None]: def callback(_ctx: click.Context, _param: click.Parameter, cli_value: Any) -> None: if cli_value is None: return raise SystemExit( f"Setting {config_option.key!r} option using the CLI flag is not allowed. " f"Set this option in the configuration file or environment " f"variable: {config_option.env_var!r}" ) return callback F = TypeVar("F", bound=Callable[..., Any]) def configurator_options(func: F) -> F: """Decorator that adds config param keys to click dynamically.""" for _, value in reversed(_config._config_options_template.items()): parsed_parameter = _convert_config_option_to_click_option(value) if value.sensitive: # Display a warning if the user tries to set sensitive # options using the CLI and exit with non-zero code. click_option_kwargs = { "expose_value": False, "hidden": True, "is_eager": True, "callback": _make_sensitive_option_callback(value), } else: click_option_kwargs = { "show_envvar": True, "envvar": parsed_parameter["envvar"], } config_option = click.option( parsed_parameter["option"], parsed_parameter["param"], help=parsed_parameter["description"], type=parsed_parameter["type"], multiple=parsed_parameter["multiple"], **click_option_kwargs, # type: ignore ) func = config_option(func) return func def _download_remote(main_script_path: str, url_path: str) -> None: """Fetch remote file at url_path to main_script_path.""" import requests from requests.exceptions import RequestException with open(main_script_path, "wb") as fp: try: resp = requests.get(url_path, timeout=30) resp.raise_for_status() fp.write(resp.content) except RequestException as e: raise click.BadParameter(f"Unable to fetch {url_path}.\n{e}") @click.group(context_settings={"auto_envvar_prefix": "STREAMLIT"}) @click.option("--log_level", show_default=True, type=click.Choice(LOG_LEVELS)) @click.version_option(prog_name="Streamlit") def main(log_level: str = "info") -> None: """Try out a demo with: $ streamlit hello Or use the line below to run your own script: $ streamlit run your_script.py """ # noqa: D400 if log_level: from streamlit.logger import get_logger logger: Final = get_logger(__name__) logger.warning( "Setting the log level using the --log_level flag is unsupported." "\nUse the --logger.level flag (after your streamlit command) instead." ) @main.command("help") def help() -> None: # noqa: A001 """Print this help message.""" # We use _get_command_line_as_string to run some error checks but don't do # anything with its return value. _get_command_line_as_string() # Pretend user typed 'streamlit --help' instead of 'streamlit help'. sys.argv[1] = "--help" main(prog_name="streamlit") @main.command("version") def main_version() -> None: """Print Streamlit's version number.""" # Pretend user typed 'streamlit --version' instead of 'streamlit version' import sys # We use _get_command_line_as_string to run some error checks but don't do # anything with its return value. _get_command_line_as_string() sys.argv[1] = "--version" main() @main.command("docs") def main_docs() -> None: """Show help in browser.""" click.echo("Showing help page in browser...") from streamlit import cli_util cli_util.open_browser("https://docs.streamlit.io") @main.command("hello") @configurator_options def main_hello(**kwargs: Any) -> None: """Runs the Hello World script.""" from streamlit.hello import streamlit_app filename = streamlit_app.__file__ _main_run(filename, flag_options=kwargs) @main.command("run") @configurator_options @click.argument("target", default="streamlit_app.py", envvar="STREAMLIT_RUN_TARGET") @click.argument("args", nargs=-1) def main_run(target: str, args: list[str] | None = None, **kwargs: Any) -> None: """Run a Python script, piping stderr to Streamlit. If omitted, the target script will be assumed to be "streamlit_app.py". Otherwise, the target script should be one of the following: - The path to a local Python file. - The path to a local folder where "streamlit_app.py" can be found. - A URL pointing to a Python file. In this case Streamlit will download the file to a temporary file and run it. To pass command-line arguments to the script, add " -- " before them. For example: $ streamlit run my_app.py -- --my_arg1=123 my_arg2 ↑ Your CLI args start after this. """ from streamlit import url_util if url_util.is_url(target): from streamlit.temporary_directory import TemporaryDirectory with TemporaryDirectory() as temp_dir: from urllib.parse import urlparse url_subpath = urlparse(target).path _check_extension_or_raise(url_subpath) main_script_path = os.path.join( temp_dir, url_subpath.strip("/").rsplit("/", 1)[-1] ) # if this is a GitHub/Gist blob url, convert to a raw URL first. url = url_util.process_gitblob_url(target) _download_remote(main_script_path, url) _main_run(main_script_path, args, flag_options=kwargs) else: path = Path(target) if path.is_dir(): path /= "streamlit_app.py" path_str = str(path) _check_extension_or_raise(path_str) if not path.exists(): raise click.BadParameter(f"File does not exist: {path}") _main_run(path_str, args, flag_options=kwargs) def _check_extension_or_raise(path_str: str) -> None: _, extension = os.path.splitext(path_str) if extension[1:] not in ACCEPTED_FILE_EXTENSIONS: if extension[1:] == "": raise click.BadArgumentUsage( "Streamlit requires raw Python (.py) files, but the provided file has no extension.\n" "For more information, please see https://docs.streamlit.io" ) raise click.BadArgumentUsage( f"Streamlit requires raw Python (.py) files, not {extension}.\n" "For more information, please see https://docs.streamlit.io" ) def _get_command_line_as_string() -> str | None: import subprocess parent = click.get_current_context().parent if parent is None: return None if "streamlit.cli" in parent.command_path: raise RuntimeError( "Running streamlit via `python -m streamlit.cli <command>` is" " unsupported. Please use `python -m streamlit <command>` instead." ) cmd_line_as_list = [parent.command_path] cmd_line_as_list.extend(sys.argv[1:]) return subprocess.list2cmdline(cmd_line_as_list) def _main_run( file: str, args: list[str] | None = None, flag_options: dict[str, Any] | None = None, ) -> None: # Set the main script path to use it for config & secret files # While its a bit suboptimal, we need to store this into a module-level # variable before we load the config options via `load_config_options` _config._main_script_path = os.path.abspath(file) bootstrap.load_config_options(flag_options=flag_options or {}) if args is None: args = [] if flag_options is None: flag_options = {} is_hello = _get_command_line_as_string() == "streamlit hello" check_credentials() bootstrap.run(file, is_hello, args, flag_options) # SUBCOMMAND cache @main.group("cache") def cache() -> None: """Manage the Streamlit cache.""" pass @cache.command("clear") def cache_clear() -> None: """Clear st.cache_data and st.cache_resource caches.""" # in this `streamlit cache clear` cli command we cannot use the # `cache_storage_manager from runtime (since runtime is not initialized) # so we create a new cache_storage_manager instance that used in runtime, # and call clear_all() method for it. # This will not remove the in-memory cache. cache_storage_manager = create_default_cache_storage_manager() cache_storage_manager.clear_all() caching.cache_resource.clear() # SUBCOMMAND config @main.group("config") def config() -> None: """Manage Streamlit's config settings.""" pass @config.command("show") @configurator_options def config_show(**kwargs: Any) -> None: """Show all of Streamlit's config settings.""" bootstrap.load_config_options(flag_options=kwargs) _config.show_config() # SUBCOMMAND activate @main.group("activate", invoke_without_command=True) @click.pass_context def activate(ctx: click.Context) -> None: """Activate Streamlit by entering your email.""" if not ctx.invoked_subcommand: Credentials.get_current().activate() @activate.command("reset") def activate_reset() -> None: """Reset Activation Credentials.""" Credentials.get_current().reset() # SUBCOMMAND test @main.group("test", hidden=True) def test() -> None: """Internal-only commands used for testing. These commands are not included in the output of `streamlit help`. """ pass @test.command("prog_name") def test_prog_name() -> None: """Assert that the program name is set to `streamlit test`. This is used by our cli-smoke-tests to verify that the program name is set to `streamlit ...` whether the streamlit binary is invoked directly or via `python -m streamlit ...`. """ # We use _get_command_line_as_string to run some error checks but don't do # anything with its return value. _get_command_line_as_string() parent = click.get_current_context().parent if parent is None: raise AssertionError("parent is None") if parent.command_path != "streamlit test": raise AssertionError( f"Parent command path is {parent.command_path} not streamlit test." ) @main.command("init") @click.argument("directory", required=False) def main_init(directory: str | None = None) -> None: """Initialize a new Streamlit project. If DIRECTORY is specified, create it and initialize the project there. Otherwise use the current directory. """ from pathlib import Path project_dir = Path(directory) if directory else Path.cwd() try: project_dir.mkdir(exist_ok=True, parents=True) except OSError as e: raise click.ClickException(f"Failed to create directory: {e}") # Create requirements.txt (project_dir / "requirements.txt").write_text("streamlit\n", encoding="utf-8") # Create streamlit_app.py (project_dir / "streamlit_app.py").write_text( """import streamlit as st st.title("🎈 My new app") st.write( "Let's start building! For help and inspiration, head over to [docs.streamlit.io](https://docs.streamlit.io/)." ) """, encoding="utf-8", ) rel_path_str = str(directory) if directory else "." click.secho("✨ Created new Streamlit app in ", nl=False) click.secho(f"{rel_path_str}", fg="blue") click.echo("🚀 Run it with: ", nl=False) click.secho(f"streamlit run {rel_path_str}/streamlit_app.py", fg="blue") if click.confirm("❓ Run the app now?", default=True): app_path = project_dir / "streamlit_app.py" click.echo("\nStarting Streamlit...") _main_run(str(app_path)) if __name__ == "__main__": main()
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/component_request_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Final, cast import tornado.web import streamlit.web.server.routes from streamlit.logger import get_logger from streamlit.web.server.component_file_utils import ( build_safe_abspath, guess_content_type, ) if TYPE_CHECKING: from streamlit.components.types.base_component_registry import BaseComponentRegistry _LOGGER: Final = get_logger(__name__) class ComponentRequestHandler(tornado.web.RequestHandler): def initialize(self, registry: BaseComponentRegistry) -> None: self._registry = registry def get(self, path: str) -> None: parts = path.split("/") component_name = parts[0] component_root = self._registry.get_component_path(component_name) if component_root is None: self.write("not found") self.set_status(404) return # Build a safe absolute path within the component root filename = "/".join(parts[1:]) abspath = build_safe_abspath(component_root, filename) if abspath is None: self.write("forbidden") self.set_status(403) return try: with open(abspath, "rb") as file: contents = file.read() except OSError: sanitized_abspath = abspath.replace("\n", "").replace("\r", "") _LOGGER.exception( "ComponentRequestHandler: GET %s read error", sanitized_abspath ) self.write("read error") self.set_status(404) return self.write(contents) self.set_header("Content-Type", self.get_content_type(abspath)) self.set_extra_headers(path) def set_extra_headers(self, path: str) -> None: """Disable cache for HTML files. Other assets like JS and CSS are suffixed with their hash, so they can be cached indefinitely. """ is_index_url = len(path) == 0 if is_index_url or path.endswith(".html"): self.set_header("Cache-Control", "no-cache") else: self.set_header("Cache-Control", "public") def set_default_headers(self) -> None: if streamlit.web.server.routes.allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif streamlit.web.server.routes.is_allowed_origin( origin := self.request.headers.get("Origin") ): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self) -> None: """/OPTIONS handler for preflight CORS checks.""" self.set_status(204) self.finish() @staticmethod def get_content_type(abspath: str) -> str: """Returns the ``Content-Type`` header to be used for this request. From tornado.web.StaticFileHandler. """ return guess_content_type(abspath) @staticmethod def get_url(file_id: str) -> str: """Return the URL for a component file with the given ID.""" return f"components/{file_id}"
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/__init__.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from streamlit.web.server.component_request_handler import ComponentRequestHandler from streamlit.web.server.routes import ( allow_all_cross_origin_requests, is_allowed_origin, ) from streamlit.web.server.server import Server, server_address_is_unix_socket from streamlit.web.server.stats_request_handler import StatsRequestHandler __all__ = [ "ComponentRequestHandler", "Server", "StatsRequestHandler", "allow_all_cross_origin_requests", "is_allowed_origin", "server_address_is_unix_socket", ]
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/routes.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os import re from typing import TYPE_CHECKING, Any, Final, cast import tornado.web from streamlit import config, file_util from streamlit.web.server.server_util import ( allowlisted_origins, emit_endpoint_deprecation_notice, is_xsrf_enabled, ) if TYPE_CHECKING: from collections.abc import Awaitable, Callable, Sequence # Files that match this pattern do not get cached. NO_CACHE_PATTERN = re.compile(r"(?:\.html$|^manifest\.json$)") # The max-age value to send with cached assets. Set to one year. STATIC_ASSET_CACHE_MAX_AGE_SECONDS: Final = 365 * 24 * 60 * 60 def allow_all_cross_origin_requests() -> bool: """True if cross-origin requests from any origin are allowed. We only allow ALL cross-origin requests when CORS protection has been disabled with server.enableCORS=False or if using the Node server in dev mode. When in dev mode, we have a dev and prod port, which count as two origins. """ return not config.get_option("server.enableCORS") or config.get_option( "global.developmentMode" ) def is_allowed_origin(origin: Any) -> bool: if not isinstance(origin, str): return False return origin in allowlisted_origins() class StaticFileHandler(tornado.web.StaticFileHandler): def initialize( self, path: str, default_filename: str | None = None, reserved_paths: Sequence[str] = (), ) -> None: self._reserved_paths = reserved_paths super().initialize(path, default_filename) def set_extra_headers(self, path: str) -> None: """Disable cache for HTML files and manifest.json. Other assets like JS and CSS are suffixed with their hash, so they can be cached indefinitely. """ is_index_url = len(path) == 0 if is_index_url or NO_CACHE_PATTERN.search(path): self.set_header("Cache-Control", "no-cache") else: # For all other static files suffixed with their hash, we set a long cache time. self.set_header( "Cache-Control", f"public, immutable, max-age={STATIC_ASSET_CACHE_MAX_AGE_SECONDS}", ) def validate_absolute_path(self, root: str, absolute_path: str) -> str | None: try: return super().validate_absolute_path(root, absolute_path) except tornado.web.HTTPError as e: # If the file is not found, and there are no reserved paths, # we try to serve the default file and allow the frontend to handle the issue. if e.status_code == 404: url_path = self.path # self.path is OS specific file path, we convert it to a URL path # for checking it against reserved paths. if os.path.sep != "/": url_path = url_path.replace(os.path.sep, "/") if any(url_path.endswith(x) for x in self._reserved_paths): raise self.path = self.parse_url_path(self.default_filename or "index.html") absolute_path = self.get_absolute_path(self.root, self.path) return super().validate_absolute_path(root, absolute_path) raise def write_error(self, status_code: int, **kwargs: Any) -> None: if status_code == 404: index_file = os.path.join(file_util.get_static_dir(), "index.html") self.render(index_file) else: super().write_error(status_code, **kwargs) class AddSlashHandler(tornado.web.RequestHandler): @tornado.web.addslash def get(self) -> None: pass class RemoveSlashHandler(tornado.web.RequestHandler): @tornado.web.removeslash def get(self) -> None: pass class _SpecialRequestHandler(tornado.web.RequestHandler): """Superclass for "special" endpoints, like /healthz.""" def set_default_headers(self) -> None: self.set_header("Cache-Control", "no-cache") if allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif is_allowed_origin(origin := self.request.headers.get("Origin")): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self) -> None: """/OPTIONS handler for preflight CORS checks. When a browser is making a CORS request, it may sometimes first send an OPTIONS request, to check whether the server understands the CORS protocol. This is optional, and doesn't happen for every request or in every browser. If an OPTIONS request does get sent, and is not then handled by the server, the browser will fail the underlying request. The proper way to handle this is to send a 204 response ("no content") with the CORS headers attached. (These headers are automatically added to every outgoing response, including OPTIONS responses, via set_default_headers().) See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request """ self.set_status(204) self.finish() class HealthHandler(_SpecialRequestHandler): def initialize(self, callback: Callable[[], Awaitable[tuple[bool, str]]]) -> None: """Initialize the handler. Parameters ---------- callback : callable A function that returns True if the server is healthy """ self._callback = callback async def get(self) -> None: await self.handle_request() # Some monitoring services only support the HTTP HEAD method for requests to # healthcheck endpoints, so we support HEAD as well to play nicely with them. async def head(self) -> None: await self.handle_request() async def handle_request(self) -> None: if self.request.uri and "_stcore/" not in self.request.uri: new_path = ( "/_stcore/script-health-check" if "script-health-check" in self.request.uri else "/_stcore/health" ) emit_endpoint_deprecation_notice(self, new_path=new_path) ok, msg = await self._callback() if ok: self.write(msg) self.set_status(200) # Tornado will set the _streamlit_xsrf cookie automatically for the page on # request for the document. However, if the server is reset and # server.enableXsrfProtection is updated, the browser does not reload the document. # Manually setting the cookie on /healthz since it is pinged when the # browser is disconnected from the server. if is_xsrf_enabled(): cookie_kwargs = self.settings.get("xsrf_cookie_kwargs", {}) self.set_cookie( self.settings.get("xsrf_cookie_name", "_streamlit_xsrf"), self.xsrf_token, **cookie_kwargs, ) else: # 503 = SERVICE_UNAVAILABLE self.set_status(503) self.write(msg) _DEFAULT_ALLOWED_MESSAGE_ORIGINS = [ # Community-cloud related domains. # We can remove these in the future if community cloud # provides those domains via the host-config endpoint. "https://devel.streamlit.test", "https://*.streamlit.apptest", "https://*.streamlitapp.test", "https://*.streamlitapp.com", "https://share.streamlit.io", "https://share-demo.streamlit.io", "https://share-head.streamlit.io", "https://share-staging.streamlit.io", "https://*.demo.streamlit.run", "https://*.head.streamlit.run", "https://*.staging.streamlit.run", "https://*.streamlit.run", "https://*.demo.streamlit.app", "https://*.head.streamlit.app", "https://*.staging.streamlit.app", "https://*.streamlit.app", ] class HostConfigHandler(_SpecialRequestHandler): def initialize(self) -> None: # Make a copy of the allowedOrigins list, since we might modify it later: self._allowed_origins = _DEFAULT_ALLOWED_MESSAGE_ORIGINS.copy() if ( config.get_option("global.developmentMode") and "http://localhost" not in self._allowed_origins ): # Allow messages from localhost in dev mode for testing of host <-> guest communication self._allowed_origins.append("http://localhost") async def get(self) -> None: self.write( { "allowedOrigins": self._allowed_origins, "useExternalAuthToken": False, # Default host configuration settings. "enableCustomParentMessages": False, "enforceDownloadInNewTab": False, "metricsUrl": "", "blockErrorDialogs": False, # Determines whether the crossOrigin attribute is set on some elements, e.g. img, video, audio, and if # so with which value. One of None, "anonymous", "use-credentials". "resourceCrossOriginMode": None, } ) self.set_status(200)
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/media_file_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import Any, cast from urllib.parse import quote import tornado.web from streamlit.logger import get_logger from streamlit.runtime.media_file_storage import MediaFileKind, MediaFileStorageError from streamlit.runtime.memory_media_file_storage import ( MemoryMediaFileStorage, get_extension_for_mimetype, ) from streamlit.web.server import allow_all_cross_origin_requests, is_allowed_origin _LOGGER = get_logger(__name__) class MediaFileHandler(tornado.web.StaticFileHandler): _storage: MemoryMediaFileStorage @classmethod def initialize_storage(cls, storage: MemoryMediaFileStorage) -> None: """Set the MemoryMediaFileStorage object used by instances of this handler. Must be called on server startup. """ # This is a class method, rather than an instance method, because # `get_content()` is a class method and needs to access the storage # instance. cls._storage = storage def set_default_headers(self) -> None: if allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif is_allowed_origin(origin := self.request.headers.get("Origin")): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def set_extra_headers(self, path: str) -> None: """Add Content-Disposition header for downloadable files. Set header value to "attachment" indicating that file should be saved locally instead of displaying inline in browser. We also set filename to specify the filename for downloaded files. Used for serving downloadable files, like files stored via the `st.download_button` widget. """ media_file = self._storage.get_file(path) if media_file and media_file.kind == MediaFileKind.DOWNLOADABLE: filename = media_file.filename if not filename: filename = f"streamlit_download{get_extension_for_mimetype(media_file.mimetype)}" try: # Check that the value can be encoded in latin1. Latin1 is # the default encoding for headers. filename.encode("latin1") file_expr = f'filename="{filename}"' except UnicodeEncodeError: # RFC5987 syntax. # See: https://datatracker.ietf.org/doc/html/rfc5987 file_expr = f"filename*=utf-8''{quote(filename)}" self.set_header("Content-Disposition", f"attachment; {file_expr}") # Overriding StaticFileHandler to use the MediaFileManager # # From the Tornado docs: # To replace all interaction with the filesystem (e.g. to serve # static content from a database), override `get_content`, # `get_content_size`, `get_modified_time`, `get_absolute_path`, and # `validate_absolute_path`. def validate_absolute_path( self, root: str, # noqa: ARG002 absolute_path: str, ) -> str: try: self._storage.get_file(absolute_path) except MediaFileStorageError: _LOGGER.exception("MediaFileHandler: Missing file %s", absolute_path) raise tornado.web.HTTPError(404, "not found") return absolute_path def get_content_size(self) -> int: abspath = self.absolute_path if abspath is None: return 0 media_file = self._storage.get_file(abspath) return media_file.content_size def get_modified_time(self) -> None: # We do not track last modified time, but this can be improved to # allow caching among files in the MediaFileManager return None @classmethod def get_absolute_path(cls, root: str, path: str) -> str: # noqa: ARG003 # All files are stored in memory, so the absolute path is just the # path itself. In the MediaFileHandler, it's just the filename return path @classmethod def get_content( cls, abspath: str, start: int | None = None, end: int | None = None ) -> Any: _LOGGER.debug("MediaFileHandler: GET %s", abspath) try: # abspath is the hash as used `get_absolute_path` media_file = cls._storage.get_file(abspath) except Exception: _LOGGER.exception("MediaFileHandler: Missing file %s", abspath) return None _LOGGER.debug( "MediaFileHandler: Sending %s file %s", media_file.mimetype, abspath ) # If there is no start and end, just return the full content if start is None and end is None: return media_file.content if start is None: start = 0 if end is None: end = len(media_file.content) # content is bytes that work just by slicing supplied by start and end return media_file.content[start:end]
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/server_util.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Server related utility functions.""" from __future__ import annotations from typing import TYPE_CHECKING, Final, Literal, cast from urllib.parse import urljoin from streamlit import config, net_util, url_util from streamlit.runtime.secrets import secrets_singleton from streamlit.type_util import is_version_less_than if TYPE_CHECKING: from collections.abc import Callable from tornado.web import RequestHandler # The port used for internal development. DEVELOPMENT_PORT: Final = 3000 AUTH_COOKIE_NAME: Final = "_streamlit_user" def allowlisted_origins() -> set[str]: return {origin.strip() for origin in config.get_option("server.corsAllowedOrigins")} def is_tornado_version_less_than(v: str) -> bool: """Return True if the current Tornado version is less than the input version. Parameters ---------- v : str Version string, e.g. "0.25.0" Returns ------- bool Raises ------ InvalidVersion If the version strings are not valid. """ import tornado return is_version_less_than(tornado.version, v) def is_url_from_allowed_origins(url: str) -> bool: """Return True if URL is from allowed origins (for CORS purpose). Allowed origins: 1. localhost 2. The internal and external IP addresses of the machine where this function was called from. If `server.enableCORS` is False, this allows all origins. """ if not config.get_option("server.enableCORS"): # Allow everything when CORS is disabled. return True hostname = url_util.get_hostname(url) allowlisted_domains = [ url_util.get_hostname(origin) for origin in allowlisted_origins() ] allowed_domains: list[str | None | Callable[[], str | None]] = [ # Check localhost first. "localhost", "0.0.0.0", # noqa: S104 "127.0.0.1", # Try to avoid making unnecessary HTTP requests by checking if the user # manually specified a server address. _get_server_address_if_manually_set, # Then try the options that depend on HTTP requests or opening sockets. net_util.get_internal_ip, net_util.get_external_ip, *allowlisted_domains, ] for allowed_domain in allowed_domains: allowed_domain_str = ( allowed_domain() if callable(allowed_domain) else allowed_domain ) if allowed_domain_str is None: continue if hostname == allowed_domain_str: return True return False def get_cookie_secret() -> str: """Get the cookie secret. If the user has not set a cookie secret, we generate a random one. """ cookie_secret: str = config.get_option("server.cookieSecret") if secrets_singleton.load_if_toml_exists(): auth_section = secrets_singleton.get("auth") if auth_section: cookie_secret = auth_section.get("cookie_secret", cookie_secret) return cookie_secret def is_xsrf_enabled() -> bool: csrf_enabled = config.get_option("server.enableXsrfProtection") if not csrf_enabled and secrets_singleton.load_if_toml_exists(): auth_section = secrets_singleton.get("auth", None) csrf_enabled = csrf_enabled or auth_section is not None return cast("bool", csrf_enabled) def _get_server_address_if_manually_set() -> str | None: if config.is_manually_set("browser.serverAddress"): return url_util.get_hostname(config.get_option("browser.serverAddress")) return None def make_url_path_regex( *path: str, trailing_slash: Literal["optional", "required", "prohibited"] = "optional", ) -> str: """Get a regex of the form ^/foo/bar/baz/?$ for a path (foo, bar, baz).""" filtered_paths = [x.strip("/") for x in path if x] # Filter out falsely components. path_format = r"^/%s$" if trailing_slash == "optional": path_format = r"^/%s/?$" elif trailing_slash == "required": path_format = r"^/%s/$" return path_format % "/".join(filtered_paths) def get_url(host_ip: str) -> str: """Get the URL for any app served at the given host_ip. Parameters ---------- host_ip : str The IP address of the machine that is running the Streamlit Server. Returns ------- str The URL. """ protocol = "https" if config.get_option("server.sslCertFile") else "http" port = _get_browser_address_bar_port() base_path = config.get_option("server.baseUrlPath").strip("/") if base_path: base_path = "/" + base_path host_ip = host_ip.strip("/") return f"{protocol}://{host_ip}:{port}{base_path}" def _get_browser_address_bar_port() -> int: """Get the app URL that will be shown in the browser's address bar. That is, this is the port where static assets will be served from. In dev, this is different from the URL that will be used to connect to the server-browser websocket. """ if config.get_option("global.developmentMode"): return DEVELOPMENT_PORT return int(config.get_option("browser.serverPort")) def emit_endpoint_deprecation_notice(handler: RequestHandler, new_path: str) -> None: """Emits the warning about deprecation of HTTP endpoint in the HTTP header.""" handler.set_header("Deprecation", True) new_url = urljoin(f"{handler.request.protocol}://{handler.request.host}", new_path) handler.set_header("Link", f'<{new_url}>; rel="alternate"')
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/browser_websocket_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import hmac import json from typing import TYPE_CHECKING, Any, Final from urllib.parse import urlparse import tornado.concurrent import tornado.locks import tornado.netutil import tornado.web import tornado.websocket from tornado.escape import utf8 from tornado.websocket import WebSocketHandler from streamlit import config from streamlit.logger import get_logger from streamlit.proto.BackMsg_pb2 import BackMsg from streamlit.runtime import Runtime, SessionClient, SessionClientDisconnectedError from streamlit.runtime.runtime_util import serialize_forward_msg from streamlit.web.server.server_util import ( AUTH_COOKIE_NAME, is_url_from_allowed_origins, is_xsrf_enabled, ) if TYPE_CHECKING: from collections.abc import Awaitable from streamlit.proto.ForwardMsg_pb2 import ForwardMsg _LOGGER: Final = get_logger(__name__) class BrowserWebSocketHandler(WebSocketHandler, SessionClient): """Handles a WebSocket connection from the browser.""" def initialize(self, runtime: Runtime) -> None: self._runtime = runtime self._session_id: str | None = None # The XSRF cookie is normally set when xsrf_form_html is used, but in a # pure-Javascript application that does not use any regular forms we just # need to read the self.xsrf_token manually to set the cookie as a side # effect. See https://www.tornadoweb.org/en/stable/guide/security.html#cross-site-request-forgery-protection # for more details. if is_xsrf_enabled(): _ = self.xsrf_token def get_signed_cookie( self, name: str, value: str | None = None, max_age_days: float = 31, min_version: int | None = None, ) -> bytes | None: """Get a signed cookie from the request. Added for compatibility with Tornado < 6.3.0. See release notes: https://www.tornadoweb.org/en/stable/releases/v6.3.0.html#deprecation-notices """ try: return super().get_signed_cookie(name, value, max_age_days, min_version) except AttributeError: return super().get_secure_cookie(name, value, max_age_days, min_version) def check_origin(self, origin: str) -> bool: """Set up CORS.""" return super().check_origin(origin) or is_url_from_allowed_origins(origin) def _validate_xsrf_token(self, supplied_token: str) -> bool: """Inspired by tornado.web.RequestHandler.check_xsrf_cookie method, to check the XSRF token passed in Websocket connection header. """ _, token, _ = self._decode_xsrf_token(supplied_token) _, expected_token, _ = self._get_raw_xsrf_token() decoded_token = utf8(token) decoded_expected_token = utf8(expected_token) if not decoded_token or not decoded_expected_token: return False return hmac.compare_digest(decoded_token, decoded_expected_token) def _parse_user_cookie(self, raw_cookie_value: bytes) -> dict[str, Any]: """Process the user cookie and extract the user info after validating the origin. Origin is validated for security reasons. """ cookie_value = json.loads(raw_cookie_value) user_info = {} cookie_value_origin = cookie_value.get("origin", None) parsed_origin_from_header = urlparse(self.request.headers["Origin"]) expected_origin_value = ( parsed_origin_from_header.scheme + "://" + parsed_origin_from_header.netloc ) if cookie_value_origin == expected_origin_value: user_info["is_logged_in"] = cookie_value.get("is_logged_in", False) del cookie_value["origin"] del cookie_value["is_logged_in"] user_info.update(cookie_value) else: _LOGGER.error( "Origin mismatch, the origin of websocket request is not the " "same origin of redirect_uri in secrets.toml", ) return user_info def write_forward_msg(self, msg: ForwardMsg) -> None: """Send a ForwardMsg to the browser.""" try: self.write_message(serialize_forward_msg(msg), binary=True) except tornado.websocket.WebSocketClosedError as e: raise SessionClientDisconnectedError from e def select_subprotocol(self, subprotocols: list[str]) -> str | None: """Return the first subprotocol in the given list. This method is used by Tornado to select a protocol when the Sec-WebSocket-Protocol header is set in an HTTP Upgrade request. NOTE: We repurpose the Sec-WebSocket-Protocol header here in a slightly unfortunate (but necessary) way. The browser WebSocket API doesn't allow us to set arbitrary HTTP headers, and this header is the only one where we have the ability to set it to arbitrary values, so we use it to pass tokens (in this case, the previous session ID to allow us to reconnect to it) from client to server as the *third* value in the list. The reason why the auth token is set as the third value is that: - when Sec-WebSocket-Protocol is set, many clients expect the server to respond with a selected subprotocol to use. We don't want that reply to be the session token, so we by convention have the client always set the first protocol to "streamlit" and select that. - the second protocol in the list is reserved in some deployment environments for an auth token that we currently don't use """ if subprotocols: return subprotocols[0] return None def open(self, *args: Any, **kwargs: Any) -> Awaitable[None] | None: user_info: dict[str, str | bool | None] = {} existing_session_id = None try: ws_protocols = [ p.strip() for p in self.request.headers["Sec-Websocket-Protocol"].split(",") ] raw_cookie_value = self.get_signed_cookie(AUTH_COOKIE_NAME) if is_xsrf_enabled() and raw_cookie_value: csrf_protocol_value = ws_protocols[1] if self._validate_xsrf_token(csrf_protocol_value): user_info.update(self._parse_user_cookie(raw_cookie_value)) if len(ws_protocols) >= 3: # See the NOTE in the docstring of the `select_subprotocol` method above # for a detailed explanation of why this is done. existing_session_id = ws_protocols[2] except KeyError: # Just let existing_session_id=None if we run into any error while trying to # extract it from the Sec-Websocket-Protocol header. pass # Map in any user-configured headers. Note that these override anything coming # from the auth cookie. mapping_config = config.get_option("server.trustedUserHeaders") for header_name, user_info_key in mapping_config.items(): header_values = self.request.headers.get_list(header_name) if header_values: # If there's at least one value, use the first value. # NOTE: Tornado doesn't document the order of these values, so it's # possible this won't be the first value that was received by the # server. user_info[user_info_key] = header_values[0] else: # Default to explicit None. user_info[user_info_key] = None self._session_id = self._runtime.connect_session( client=self, user_info=user_info, existing_session_id=existing_session_id, ) return None def on_close(self) -> None: if not self._session_id: return self._runtime.disconnect_session(self._session_id) self._session_id = None def get_compression_options(self) -> dict[Any, Any] | None: """Enable WebSocket compression. Returning an empty dict enables websocket compression. Returning None disables it. (See the docstring in the parent class.) """ if config.get_option("server.enableWebsocketCompression"): return {} return None def on_message(self, payload: str | bytes) -> None: if not self._session_id: return try: if isinstance(payload, str): # Sanity check. (The frontend should only be sending us bytes; # Protobuf.ParseFromString does not accept str input.) raise TypeError( # noqa: TRY301 "WebSocket received an unexpected `str` message. " "(We expect `bytes` only.)" ) msg = BackMsg() msg.ParseFromString(payload) _LOGGER.debug("Received the following back message:\n%s", msg) except Exception as ex: _LOGGER.exception("Error deserializing back message") self._runtime.handle_backmsg_deserialization_exception(self._session_id, ex) return # "debug_disconnect_websocket" and "debug_shutdown_runtime" are special # developmentMode-only messages used in e2e tests to test reconnect handling and # disabling widgets. if msg.WhichOneof("type") == "debug_disconnect_websocket": if config.get_option("global.developmentMode") or config.get_option( "global.e2eTest" ): self.close() else: _LOGGER.warning( "Client tried to disconnect websocket when not in development mode or e2e testing." ) elif msg.WhichOneof("type") == "debug_shutdown_runtime": if config.get_option("global.developmentMode") or config.get_option( "global.e2eTest" ): self._runtime.stop() else: _LOGGER.warning( "Client tried to shut down runtime when not in development mode or e2e testing." ) else: # AppSession handles all other BackMsg types. self._runtime.handle_backmsg(self._session_id, msg)
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/stats_request_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, cast import tornado.web from streamlit.web.server import allow_all_cross_origin_requests, is_allowed_origin from streamlit.web.server.server_util import emit_endpoint_deprecation_notice if TYPE_CHECKING: from streamlit.proto.openmetrics_data_model_pb2 import MetricSet as MetricSetProto from streamlit.runtime.stats import CacheStat, StatsManager class StatsRequestHandler(tornado.web.RequestHandler): def initialize(self, stats_manager: StatsManager) -> None: self._manager = stats_manager def set_default_headers(self) -> None: if allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif is_allowed_origin(origin := self.request.headers.get("Origin")): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self) -> None: """/OPTIONS handler for preflight CORS checks.""" self.set_status(204) self.finish() def get(self) -> None: if self.request.uri and "_stcore/" not in self.request.uri: emit_endpoint_deprecation_notice(self, new_path="/_stcore/metrics") stats = self._manager.get_stats() # If the request asked for protobuf output, we return a serialized # protobuf. Else we return text. if "application/x-protobuf" in self.request.headers.get_list("Accept"): self.write(self._stats_to_proto(stats).SerializeToString()) self.set_header("Content-Type", "application/x-protobuf") self.set_status(200) else: self.write(self._stats_to_text(self._manager.get_stats())) self.set_header("Content-Type", "application/openmetrics-text") self.set_status(200) @staticmethod def _stats_to_text(stats: list[CacheStat]) -> str: metric_type = "# TYPE cache_memory_bytes gauge" metric_unit = "# UNIT cache_memory_bytes bytes" metric_help = "# HELP Total memory consumed by a cache." openmetrics_eof = "# EOF\n" # Format: header, stats, EOF result = [metric_type, metric_unit, metric_help] result.extend(stat.to_metric_str() for stat in stats) result.append(openmetrics_eof) return "\n".join(result) @staticmethod def _stats_to_proto(stats: list[CacheStat]) -> MetricSetProto: # Lazy load the import of this proto message for better performance: from streamlit.proto.openmetrics_data_model_pb2 import GAUGE from streamlit.proto.openmetrics_data_model_pb2 import ( MetricSet as MetricSetProto, ) metric_set = MetricSetProto() metric_family = metric_set.metric_families.add() metric_family.name = "cache_memory_bytes" metric_family.type = GAUGE metric_family.unit = "bytes" metric_family.help = "Total memory consumed by a cache." for stat in stats: metric_proto = metric_family.metrics.add() stat.marshall_metric_proto(metric_proto) metric_set = MetricSetProto() metric_set.metric_families.append(metric_family) return metric_set
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/oauth_authlib_routes.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import json from typing import Any, Final, cast from urllib.parse import urlparse import tornado.web from streamlit.auth_util import ( AuthCache, decode_provider_token, generate_default_provider_section, get_secrets_auth_section, ) from streamlit.errors import StreamlitAuthError from streamlit.logger import get_logger from streamlit.url_util import make_url_path from streamlit.web.server.oidc_mixin import TornadoOAuth, TornadoOAuth2App from streamlit.web.server.server_util import AUTH_COOKIE_NAME _LOGGER: Final = get_logger(__name__) auth_cache = AuthCache() def create_oauth_client(provider: str) -> tuple[TornadoOAuth2App, str]: """Create an OAuth client for the given provider based on secrets.toml configuration.""" auth_section = get_secrets_auth_section() if auth_section: redirect_uri = auth_section.get("redirect_uri", None) config = auth_section.to_dict() else: config = {} redirect_uri = "/" provider_section = config.setdefault(provider, {}) if not provider_section and provider == "default": provider_section = generate_default_provider_section(auth_section) config["default"] = provider_section provider_client_kwargs = provider_section.setdefault("client_kwargs", {}) if "scope" not in provider_client_kwargs: provider_client_kwargs["scope"] = "openid email profile" if "prompt" not in provider_client_kwargs: provider_client_kwargs["prompt"] = "select_account" oauth = TornadoOAuth(config, cache=auth_cache) oauth.register(provider) return oauth.create_client(provider), redirect_uri # type: ignore[no-untyped-call] class AuthHandlerMixin(tornado.web.RequestHandler): """Mixin for handling auth cookies. Added for compatibility with Tornado < 6.3.0.""" def initialize(self, base_url: str) -> None: self.base_url = base_url def redirect_to_base(self) -> None: self.redirect(make_url_path(self.base_url, "/")) def set_auth_cookie(self, user_info: dict[str, Any]) -> None: serialized_cookie_value = json.dumps(user_info) # log error if cookie value is larger than 4096 bytes if len(serialized_cookie_value.encode()) > 4096: _LOGGER.error( "Authentication cookie size exceeds maximum browser limit of 4096 bytes. Authentication may fail." ) try: # We don't specify Tornado secure flag here because it leads to missing cookie on Safari. # The OIDC flow should work only on secure context anyway (localhost or HTTPS), # so specifying the secure flag here will not add anything in terms of security. self.set_signed_cookie( AUTH_COOKIE_NAME, serialized_cookie_value, httpOnly=True, ) except AttributeError: self.set_secure_cookie( AUTH_COOKIE_NAME, serialized_cookie_value, httponly=True, ) def clear_auth_cookie(self) -> None: self.clear_cookie(AUTH_COOKIE_NAME) class AuthLoginHandler(AuthHandlerMixin, tornado.web.RequestHandler): async def get(self) -> None: """Redirect to the OAuth provider login page.""" provider = self._parse_provider_token() if provider is None: self.redirect_to_base() return client, redirect_uri = create_oauth_client(provider) try: client.authorize_redirect(self, redirect_uri) except Exception as e: self.send_error(400, reason=str(e)) def _parse_provider_token(self) -> str | None: provider_token = self.get_argument("provider", None) if provider_token is None: return None try: payload = decode_provider_token(provider_token) except StreamlitAuthError: return None return payload["provider"] class AuthLogoutHandler(AuthHandlerMixin, tornado.web.RequestHandler): def get(self) -> None: self.clear_auth_cookie() self.redirect_to_base() class AuthCallbackHandler(AuthHandlerMixin, tornado.web.RequestHandler): async def get(self) -> None: provider = self._get_provider_by_state() origin = self._get_origin_from_secrets() if origin is None: _LOGGER.error( "Error, misconfigured origin for `redirect_uri` in secrets. ", ) self.redirect_to_base() return error = self.get_argument("error", None) if error: error_description = self.get_argument("error_description", None) sanitized_error = error.replace("\n", "").replace("\r", "") sanitized_error_description = ( error_description.replace("\n", "").replace("\r", "") if error_description else None ) _LOGGER.error( "Error during authentication: %s. Error description: %s", sanitized_error, sanitized_error_description, ) self.redirect_to_base() return if provider is None: # See https://github.com/streamlit/streamlit/issues/13101 _LOGGER.warning( "Missing provider for OAuth callback; this often indicates a stale " "or replayed callback (for example, from browser back/forward " "navigation).", ) self.redirect_to_base() return client, _ = create_oauth_client(provider) token = client.authorize_access_token(self) user = cast("dict[str, Any]", token.get("userinfo")) cookie_value = dict(user, origin=origin, is_logged_in=True) if user: self.set_auth_cookie(cookie_value) else: _LOGGER.error( "Error, missing user info.", ) self.redirect_to_base() def _get_provider_by_state(self) -> str | None: state_code_from_url = self.get_argument("state") current_cache_keys = list(auth_cache.get_dict().keys()) state_provider_mapping = {} for key in current_cache_keys: _, _, recorded_provider, code = key.split("_") state_provider_mapping[code] = recorded_provider provider: str | None = state_provider_mapping.get(state_code_from_url) return provider def _get_origin_from_secrets(self) -> str | None: redirect_uri = None auth_section = get_secrets_auth_section() if auth_section: redirect_uri = auth_section.get("redirect_uri", None) if not redirect_uri: return None redirect_uri_parsed = urlparse(redirect_uri) origin_from_redirect_uri: str = ( redirect_uri_parsed.scheme + "://" + redirect_uri_parsed.netloc ) return origin_from_redirect_uri
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/component_file_utils.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for safely resolving component asset paths and content types. These helpers are used by server handlers to construct safe absolute paths for component files and to determine the appropriate ``Content-Type`` header for responses. Path resolution prevents directory traversal by normalizing and checking real paths against a component's root directory. """ from __future__ import annotations import mimetypes import os from typing import Final _OCTET_STREAM: Final[str] = "application/octet-stream" def build_safe_abspath(component_root: str, relative_url_path: str) -> str | None: """Build an absolute path inside ``component_root`` if safe. The function joins ``relative_url_path`` with ``component_root`` and normalizes and resolves symlinks. If the resulting path escapes the component root, ``None`` is returned to indicate a forbidden traversal. Parameters ---------- component_root : str Absolute path to the component's root directory. relative_url_path : str Relative URL path from the component root to the requested file. Returns ------- str or None The resolved absolute path if it stays within ``component_root``; otherwise ``None`` when the path would traverse outside the root. """ root_real = os.path.realpath(component_root) candidate = os.path.normpath(os.path.join(root_real, relative_url_path)) candidate_real = os.path.realpath(candidate) try: # Ensure the candidate stays within the real component root if os.path.commonpath([root_real, candidate_real]) != root_real: return None except ValueError: # On some platforms, commonpath can raise if drives differ; treat as forbidden. return None return candidate_real def guess_content_type(abspath: str) -> str: """Guess the HTTP ``Content-Type`` for a file path. This logic mirrors Tornado's ``StaticFileHandler`` by respecting encoding metadata from ``mimetypes.guess_type`` and falling back to ``application/octet-stream`` when no specific type can be determined. Parameters ---------- abspath : str Absolute file path used for type detection (only the suffix matters). Returns ------- str Guessed content type string suitable for the ``Content-Type`` header. """ mime_type, encoding = mimetypes.guess_type(abspath) # per RFC 6713, use the appropriate type for a gzip compressed file if encoding == "gzip": return "application/gzip" # As of 2015-07-21 there is no bzip2 encoding defined at # http://www.iana.org/assignments/media-types/media-types.xhtml # So for that (and any other encoding), use octet-stream. if encoding is not None: return _OCTET_STREAM if mime_type is not None: return mime_type # if mime_type not detected, use application/octet-stream return _OCTET_STREAM
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/authlib_tornado_integration.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any from authlib.integrations.base_client import ( FrameworkIntegration, ) from streamlit.runtime.secrets import AttrDict if TYPE_CHECKING: from collections.abc import Sequence from streamlit.web.server.oidc_mixin import TornadoOAuth class TornadoIntegration(FrameworkIntegration): def update_token( self, token: dict[str, Any], refresh_token: dict[str, Any] | None = None, access_token: dict[str, Any] | None = None, ) -> None: """We do not support access token refresh, since we obtain and operate only on identity tokens. We override this method explicitly to implement all abstract methods of base class. """ @staticmethod def load_config( # type: ignore[override] oauth: TornadoOAuth, name: str, params: Sequence[str] ) -> dict[str, Any]: """Configure Authlib integration with provider parameters specified in secrets.toml. """ # oauth.config here is an auth section from secrets.toml # We parse it here to transform nested AttrDict (for client_kwargs value) # to dict so Authlib can work with it under the hood. if not oauth.config: return {} prepared_config = {} for key in params: value = oauth.config.get(name, {}).get(key, None) if isinstance(value, AttrDict): # We want to modify client_kwargs further after loading server metadata value = value.to_dict() if value is not None: prepared_config[key] = value return prepared_config
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/oidc_mixin.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # mypy: disable-error-code="no-untyped-call" from __future__ import annotations from typing import TYPE_CHECKING, Any, cast from authlib.integrations.base_client import ( BaseApp, BaseOAuth, OAuth2Mixin, OAuthError, OpenIDMixin, ) from authlib.integrations.requests_client import ( OAuth2Session, ) from streamlit.web.server.authlib_tornado_integration import TornadoIntegration if TYPE_CHECKING: from collections.abc import Callable import tornado.web from streamlit.auth_util import AuthCache class TornadoOAuth2App(OAuth2Mixin, OpenIDMixin, BaseApp): client_cls = OAuth2Session def load_server_metadata(self) -> dict[str, Any]: """We enforce S256 code challenge method if it is supported by the server.""" result = cast("dict[str, Any]", super().load_server_metadata()) if "S256" in result.get("code_challenge_methods_supported", []): self.client_kwargs["code_challenge_method"] = "S256" return result def authorize_redirect( self, request_handler: tornado.web.RequestHandler, redirect_uri: Any = None, **kwargs: Any, ) -> None: """Create a HTTP Redirect for Authorization Endpoint. :param request_handler: HTTP request instance from Tornado. :param redirect_uri: Callback or redirect URI for authorization. :param kwargs: Extra parameters to include. :return: A HTTP redirect response. """ auth_context = self.create_authorization_url(redirect_uri, **kwargs) self._save_authorize_data(redirect_uri=redirect_uri, **auth_context) request_handler.redirect(auth_context["url"], status=302) def authorize_access_token( self, request_handler: tornado.web.RequestHandler, **kwargs: Any ) -> dict[str, Any]: """ :param request_handler: HTTP request instance from Tornado. :return: A token dict. """ error = request_handler.get_argument("error", None) if error: description = request_handler.get_argument("error_description", None) raise OAuthError(error=error, description=description) params = { "code": request_handler.get_argument("code"), "state": request_handler.get_argument("state"), } session = None claims_options = kwargs.pop("claims_options", None) state_data = self.framework.get_state_data(session, params.get("state")) self.framework.clear_state_data(session, params.get("state")) params = self._format_state_params(state_data, params) # type: ignore[attr-defined] token = self.fetch_access_token(**params, **kwargs) if "id_token" in token and "nonce" in state_data: userinfo = self.parse_id_token( token, nonce=state_data["nonce"], claims_options=claims_options ) token = {**token, "userinfo": userinfo} return cast("dict[str, Any]", token) def _save_authorize_data(self, **kwargs: Any) -> None: """Authlib underlying uses the concept of "session" to store state data. In Tornado, we don't have a session, so we use the framework's cache option. """ state = kwargs.pop("state", None) if state: session = None self.framework.set_state_data(session, state, kwargs) else: raise RuntimeError("Missing state value") class TornadoOAuth(BaseOAuth): oauth2_client_cls = TornadoOAuth2App framework_integration_cls = TornadoIntegration def __init__( self, config: dict[str, Any] | None = None, cache: AuthCache | None = None, fetch_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None, update_token: Callable[[dict[str, Any]], dict[str, Any]] | None = None, ): super().__init__( cache=cache, fetch_token=fetch_token, update_token=update_token ) self.config = config
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/upload_file_request_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from typing import TYPE_CHECKING, Any, cast import tornado.httputil import tornado.web from streamlit import config from streamlit.runtime.uploaded_file_manager import UploadedFileRec from streamlit.web.server import routes, server_util from streamlit.web.server.server_util import is_xsrf_enabled if TYPE_CHECKING: from collections.abc import Callable from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager class UploadFileRequestHandler(tornado.web.RequestHandler): """Implements the POST /upload_file endpoint.""" def initialize( self, file_mgr: MemoryUploadedFileManager, is_active_session: Callable[[str], bool], ) -> None: """ Parameters ---------- file_mgr : UploadedFileManager The server's singleton UploadedFileManager. All file uploads go here. is_active_session: A function that returns true if a session_id belongs to an active session. """ self._file_mgr = file_mgr self._is_active_session = is_active_session def set_default_headers(self) -> None: self.set_header("Access-Control-Allow-Methods", "PUT, OPTIONS, DELETE") self.set_header("Access-Control-Allow-Headers", "Content-Type") if is_xsrf_enabled(): self.set_header( "Access-Control-Allow-Origin", server_util.get_url(config.get_option("browser.serverAddress")), ) self.set_header("Access-Control-Allow-Headers", "X-Xsrftoken, Content-Type") self.set_header("Vary", "Origin") self.set_header("Access-Control-Allow-Credentials", "true") elif routes.allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif routes.is_allowed_origin(origin := self.request.headers.get("Origin")): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self, **kwargs: Any) -> None: """/OPTIONS handler for preflight CORS checks. When a browser is making a CORS request, it may sometimes first send an OPTIONS request, to check whether the server understands the CORS protocol. This is optional, and doesn't happen for every request or in every browser. If an OPTIONS request does get sent, and is not then handled by the server, the browser will fail the underlying request. The proper way to handle this is to send a 204 response ("no content") with the CORS headers attached. (These headers are automatically added to every outgoing response, including OPTIONS responses, via set_default_headers().) See https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request """ self.set_status(204) self.finish() def put(self, **kwargs: Any) -> None: """Receive an uploaded file and add it to our UploadedFileManager.""" args: dict[str, list[bytes]] = {} files: dict[str, list[Any]] = {} if not self.path_kwargs: # This is not expected to happen with normal Streamlit usage. self.send_error( 400, reason="No path arguments provided. Please provide a session_id and file_id in the URL.", ) return session_id = self.path_kwargs["session_id"] file_id = self.path_kwargs["file_id"] tornado.httputil.parse_body_arguments( content_type=self.request.headers["Content-Type"], body=self.request.body, arguments=args, files=files, ) try: if not self._is_active_session(session_id): self.send_error(400, reason="Invalid session_id") return except Exception as ex: self.send_error(400, reason=str(ex)) return uploaded_files: list[UploadedFileRec] = [] for flist in files.values(): uploaded_files.extend( UploadedFileRec( file_id=file_id, name=file["filename"], type=file["content_type"], data=file["body"], ) for file in flist ) if len(uploaded_files) != 1: self.send_error( 400, reason=f"Expected 1 file, but got {len(uploaded_files)}" ) return self._file_mgr.add_file(session_id=session_id, file=uploaded_files[0]) self.set_status(204) def delete(self, **kwargs: Any) -> None: """Delete file request handler.""" if not self.path_kwargs: self.send_error( 400, reason="No path arguments provided. Please provide a session_id and file_id in the URL.", ) return session_id = self.path_kwargs["session_id"] file_id = self.path_kwargs["file_id"] self._file_mgr.remove_file(session_id=session_id, file_id=file_id) self.set_status(204)
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/app_static_file_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import os from pathlib import Path from typing import Final import tornado.web from streamlit.logger import get_logger _LOGGER: Final = get_logger(__name__) # We agreed on these limitations for the initial release of static file sharing, # based on security concerns from the SiS and Community Cloud teams # The maximum possible size of single serving static file. MAX_APP_STATIC_FILE_SIZE = 200 * 1024 * 1024 # 200 MB # The list of file extensions that we serve with the corresponding Content-Type header. # All files with other extensions will be served with Content-Type: text/plain SAFE_APP_STATIC_FILE_EXTENSIONS = ( # Common image types: ".jpg", ".jpeg", ".png", ".gif", ".webp", # Common font types: ".otf", ".ttf", ".woff", ".woff2", # Other types: ".pdf", ".xml", ".json", ) class AppStaticFileHandler(tornado.web.StaticFileHandler): def initialize(self, path: str, default_filename: str | None = None) -> None: super().initialize(path, default_filename) def validate_absolute_path(self, root: str, absolute_path: str) -> str | None: full_path = os.path.abspath(absolute_path) ret_val = super().validate_absolute_path(root, absolute_path) if os.path.isdir(full_path): # we don't want to serve directories, and serve only files raise tornado.web.HTTPError(404) if os.path.commonpath([full_path, root]) != root: # Don't allow misbehaving clients to break out of the static files directory _LOGGER.warning( "Serving files outside of the static directory is not supported" ) raise tornado.web.HTTPError(404) if ( os.path.exists(full_path) and os.path.getsize(full_path) > MAX_APP_STATIC_FILE_SIZE ): raise tornado.web.HTTPError( 404, "File is too large, its size should not exceed " f"{MAX_APP_STATIC_FILE_SIZE} bytes", reason="File is too large", ) return ret_val def set_default_headers(self) -> None: # CORS protection is disabled because we need access to this endpoint # from the inner iframe. self.set_header("Access-Control-Allow-Origin", "*") def set_extra_headers(self, path: str) -> None: if Path(path).suffix not in SAFE_APP_STATIC_FILE_EXTENSIONS: self.set_header("Content-Type", "text/plain") self.set_header("X-Content-Type-Options", "nosniff")
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/bidi_component_request_handler.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Serve static assets for Custom Components v2. This module defines a Tornado ``RequestHandler`` that serves static files for Custom Components v2 from their registered component directories. Requests are resolved safely within the component's root to avoid directory traversal and are served with appropriate content type and cache headers. CORS headers are applied based on the server configuration. """ from __future__ import annotations import os from typing import TYPE_CHECKING, Final, cast import tornado.web import streamlit.web.server.routes from streamlit.logger import get_logger from streamlit.web.server.component_file_utils import ( build_safe_abspath, guess_content_type, ) if TYPE_CHECKING: from streamlit.components.v2.component_manager import BidiComponentManager _LOGGER: Final = get_logger(__name__) class BidiComponentRequestHandler(tornado.web.RequestHandler): """Request handler for serving Custom Components v2 static assets. The handler resolves a requested path to a registered component's asset within its component root, writes the file contents to the response, and sets appropriate ``Content-Type`` and cache headers. If the component or asset cannot be found, a suitable HTTP status is returned. """ def initialize(self, component_manager: BidiComponentManager) -> None: """Initialize the handler with the given component manager. Parameters ---------- component_manager : BidiComponentManager Manager used to look up registered components and their root paths. """ self._component_manager = component_manager def get(self, path: str) -> None: """Serve a component asset for the given URL path. The first path segment is interpreted as the component name. The rest of the path is resolved to a file within that component's root directory. If the file exists and is readable, its bytes are written to the response and the ``Content-Type`` header is set based on the file type. Parameters ---------- path : str Request path in the form ``"<component_name>/<relative_file>"``. Notes ----- This method writes directly to the response and sets appropriate HTTP status codes on error (``404`` for missing components/files, ``403`` for forbidden paths). """ parts = path.split("/") component_name = parts[0] component_def = self._component_manager.get(component_name) if component_def is None: self.write("not found") self.set_status(404) return # Get the component path from the component manager component_path = self._component_manager.get_component_path(component_name) if component_path is None: self.write("not found") self.set_status(404) return # Build a safe absolute path within the component root filename = "/".join(parts[1:]) # If no file segment is provided (e.g. only component name or trailing slash), # treat as not found rather than attempting to open a directory. if not filename or filename.endswith("/"): self.write("not found") self.set_status(404) return abspath = build_safe_abspath(component_path, filename) if abspath is None: self.write("forbidden") self.set_status(403) return # If the resolved path is a directory, return 404 not found. if os.path.isdir(abspath): self.write("not found") self.set_status(404) return try: with open(abspath, "rb") as file: contents = file.read() except OSError: sanitized_abspath = abspath.replace("\n", "").replace("\r", "") _LOGGER.exception( "BidiComponentRequestHandler: GET %s read error", sanitized_abspath ) self.write("read error") self.set_status(404) return self.write(contents) self.set_header("Content-Type", guess_content_type(abspath)) self.set_extra_headers(path) def set_extra_headers(self, path: str) -> None: """Disable cache for HTML files. We assume other assets like JS and CSS are suffixed with their hash, so they can be cached indefinitely. """ if path.endswith(".html"): self.set_header("Cache-Control", "no-cache") else: self.set_header("Cache-Control", "public") def set_default_headers(self) -> None: """Set default CORS headers based on server configuration. If cross-origin requests are fully allowed, ``Access-Control-Allow- Origin`` is set to ``"*"``. Otherwise, if the request ``Origin`` header is an allowed origin, the header is echoed back. """ if streamlit.web.server.routes.allow_all_cross_origin_requests(): self.set_header("Access-Control-Allow-Origin", "*") elif streamlit.web.server.routes.is_allowed_origin( origin := self.request.headers.get("Origin") ): self.set_header("Access-Control-Allow-Origin", cast("str", origin)) def options(self) -> None: """Handle preflight CORS requests. Returns ------- None Responds with HTTP ``204 No Content`` to indicate that the actual request can proceed. """ self.set_status(204) self.finish() @staticmethod def get_url(file_id: str) -> str: """Return the URL for a component asset identified by ``file_id``. Parameters ---------- file_id : str Component file identifier (typically a relative path or hashed filename). Returns ------- str Relative URL path for the resource, to be joined with the server base URL. Examples -------- >>> BidiComponentRequestHandler.get_url("my_component/main.js") '_stcore/bidi-components/my_component/main.js' """ return f"_stcore/bidi-components/{file_id}"
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/server.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import errno import logging import mimetypes import os import sys from pathlib import Path from typing import TYPE_CHECKING, Any, Final import tornado.web from tornado.httpserver import HTTPServer from streamlit import cli_util, config, file_util, util from streamlit.auth_util import is_authlib_installed from streamlit.config_option import ConfigOption from streamlit.logger import get_logger from streamlit.runtime import Runtime, RuntimeConfig, RuntimeState from streamlit.runtime.memory_media_file_storage import MemoryMediaFileStorage from streamlit.runtime.memory_session_storage import MemorySessionStorage from streamlit.runtime.memory_uploaded_file_manager import MemoryUploadedFileManager from streamlit.runtime.runtime_util import get_max_message_size_bytes from streamlit.web.cache_storage_manager_config import ( create_default_cache_storage_manager, ) from streamlit.web.server.app_static_file_handler import AppStaticFileHandler from streamlit.web.server.bidi_component_request_handler import ( BidiComponentRequestHandler, ) from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler from streamlit.web.server.component_request_handler import ComponentRequestHandler from streamlit.web.server.media_file_handler import MediaFileHandler from streamlit.web.server.routes import ( AddSlashHandler, HealthHandler, HostConfigHandler, RemoveSlashHandler, StaticFileHandler, ) from streamlit.web.server.server_util import ( get_cookie_secret, is_tornado_version_less_than, is_xsrf_enabled, make_url_path_regex, ) from streamlit.web.server.stats_request_handler import StatsRequestHandler from streamlit.web.server.upload_file_request_handler import UploadFileRequestHandler if TYPE_CHECKING: import asyncio from collections.abc import Awaitable from ssl import SSLContext _LOGGER: Final = get_logger(__name__) def _get_websocket_ping_interval_and_timeout() -> tuple[int, int]: """Get the websocket ping interval and timeout from config or defaults. Returns ------- tuple: (ping_interval, ping_timeout) """ configured_interval = config.get_option("server.websocketPingInterval") if configured_interval is not None: # User has explicitly set a value interval = int(configured_interval) # Warn if using Tornado 6.5+ with low interval if not is_tornado_version_less_than("6.5.0") and interval < 30: _LOGGER.warning( "You have set server.websocketPingInterval to %s, but Tornado >= 6.5 " "requires websocket_ping_interval >= websocket_ping_timeout. " "To comply, we are setting both the ping interval and ping timeout to %s. " "Depending on the specific deployment setup, this may cause connection issues.", interval, interval, ) # When user configures interval, set timeout to match return interval, interval # Default behavior: respect Tornado version for interval, always 30s timeout default_interval = 1 if is_tornado_version_less_than("6.5.0") else 30 return default_interval, 30 def get_tornado_settings() -> dict[str, Any]: """Get Tornado settings for the server. This is a function to allow for testing and dynamic configuration. """ ping_interval, ping_timeout = _get_websocket_ping_interval_and_timeout() return { # Gzip HTTP responses. "compress_response": True, # Ping interval for websocket keepalive. # With recent versions of Tornado, this value must be greater than or # equal to websocket_ping_timeout. # For details, see https://github.com/tornadoweb/tornado/pull/3376 # For compatibility with older versions of Tornado, we set the value to 1. "websocket_ping_interval": ping_interval, # If we don't get a ping response within this time, the connection # is timed out. "websocket_ping_timeout": ping_timeout, "xsrf_cookie_name": "_streamlit_xsrf", } # When server.port is not available it will look for the next available port # up to MAX_PORT_SEARCH_RETRIES. MAX_PORT_SEARCH_RETRIES: Final = 100 # When server.address starts with this prefix, the server will bind # to an unix socket. UNIX_SOCKET_PREFIX: Final = "unix://" # Please make sure to also update frontend/app/vite.config.ts # dev server proxy when changing or updating these endpoints as well # as the endpoints in frontend/connection/src/DefaultStreamlitEndpoints MEDIA_ENDPOINT: Final = "/media" COMPONENT_ENDPOINT: Final = "/component" BIDI_COMPONENT_ENDPOINT: Final = "/_stcore/bidi-components" STATIC_SERVING_ENDPOINT: Final = "/app/static" UPLOAD_FILE_ENDPOINT: Final = "/_stcore/upload_file" STREAM_ENDPOINT: Final = r"_stcore/stream" METRIC_ENDPOINT: Final = r"(?:st-metrics|_stcore/metrics)" MESSAGE_ENDPOINT: Final = r"_stcore/message" NEW_HEALTH_ENDPOINT: Final = "_stcore/health" HEALTH_ENDPOINT: Final = rf"(?:healthz|{NEW_HEALTH_ENDPOINT})" HOST_CONFIG_ENDPOINT: Final = r"_stcore/host-config" SCRIPT_HEALTH_CHECK_ENDPOINT: Final = ( r"(?:script-health-check|_stcore/script-health-check)" ) OAUTH2_CALLBACK_ENDPOINT: Final = "/oauth2callback" AUTH_LOGIN_ENDPOINT: Final = "/auth/login" AUTH_LOGOUT_ENDPOINT: Final = "/auth/logout" class RetriesExceededError(Exception): pass def server_port_is_manually_set() -> bool: return config.is_manually_set("server.port") def server_address_is_unix_socket() -> bool: address = config.get_option("server.address") return address is not None and address.startswith(UNIX_SOCKET_PREFIX) def start_listening(app: tornado.web.Application) -> None: """Makes the server start listening at the configured port. In case the port is already taken it tries listening to the next available port. It will error after MAX_PORT_SEARCH_RETRIES attempts. """ cert_file = config.get_option("server.sslCertFile") key_file = config.get_option("server.sslKeyFile") ssl_options = _get_ssl_options(cert_file, key_file) http_server = HTTPServer( app, max_buffer_size=config.get_option("server.maxUploadSize") * 1024 * 1024, ssl_options=ssl_options, ) if server_address_is_unix_socket(): start_listening_unix_socket(http_server) else: start_listening_tcp_socket(http_server) def _get_ssl_options(cert_file: str | None, key_file: str | None) -> SSLContext | None: if bool(cert_file) != bool(key_file): _LOGGER.error( "Options 'server.sslCertFile' and 'server.sslKeyFile' must " "be set together. Set missing options or delete existing options." ) sys.exit(1) if cert_file and key_file: # ssl_ctx.load_cert_chain raise exception as below, but it is not # sufficiently user-friendly # FileNotFoundError: [Errno 2] No such file or directory if not Path(cert_file).exists(): _LOGGER.error("Cert file '%s' does not exist.", cert_file) sys.exit(1) if not Path(key_file).exists(): _LOGGER.error("Key file '%s' does not exist.", key_file) sys.exit(1) import ssl ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) # When the SSL certificate fails to load, an exception is raised as below, # but it is not sufficiently user-friendly. # ssl.SSLError: [SSL] PEM lib (_ssl.c:4067) try: ssl_ctx.load_cert_chain(cert_file, key_file) except ssl.SSLError: _LOGGER.exception( "Failed to load SSL certificate. Make sure " "cert file '%s' and key file '%s' are correct.", cert_file, key_file, ) sys.exit(1) return ssl_ctx return None def start_listening_unix_socket(http_server: HTTPServer) -> None: address = config.get_option("server.address") file_name = os.path.expanduser(address[len(UNIX_SOCKET_PREFIX) :]) import tornado.netutil if hasattr(tornado.netutil, "bind_unix_socket"): unix_socket = tornado.netutil.bind_unix_socket(file_name) http_server.add_socket(unix_socket) else: _LOGGER.error( "Unix socket support is not available in this version of Tornado." ) sys.exit(1) def start_listening_tcp_socket(http_server: HTTPServer) -> None: call_count = 0 port = None while call_count < MAX_PORT_SEARCH_RETRIES: address = config.get_option("server.address") port = config.get_option("server.port") try: http_server.listen(port, address) break # It worked! So let's break out of the loop. except OSError as e: if e.errno == errno.EADDRINUSE: if server_port_is_manually_set(): _LOGGER.error("Port %s is already in use", port) # noqa: TRY400 sys.exit(1) else: _LOGGER.debug( "Port %s already in use, trying to use the next one.", port ) port += 1 config.set_option( "server.port", port, ConfigOption.STREAMLIT_DEFINITION ) call_count += 1 else: raise if call_count >= MAX_PORT_SEARCH_RETRIES: raise RetriesExceededError( f"Cannot start Streamlit server. Port {port} is already in use, and " f"Streamlit was unable to find a free port after {MAX_PORT_SEARCH_RETRIES} attempts.", ) class Server: def __init__(self, main_script_path: str, is_hello: bool) -> None: """Create the server. It won't be started yet.""" _set_tornado_log_levels() self.initialize_mimetypes() self._main_script_path = main_script_path # The task that runs the server if an event loop is already running. # We need to save a reference to it so that it doesn't get # garbage collected while running. self._bootstrap_task: asyncio.Task[None] | None = None # Initialize MediaFileStorage and its associated endpoint media_file_storage = MemoryMediaFileStorage(MEDIA_ENDPOINT) MediaFileHandler.initialize_storage(media_file_storage) uploaded_file_mgr = MemoryUploadedFileManager(UPLOAD_FILE_ENDPOINT) self._runtime = Runtime( RuntimeConfig( script_path=main_script_path, command_line=None, media_file_storage=media_file_storage, uploaded_file_manager=uploaded_file_mgr, cache_storage_manager=create_default_cache_storage_manager(), is_hello=is_hello, session_storage=MemorySessionStorage( ttl_seconds=config.get_option("server.disconnectedSessionTTL") ), ), ) self._runtime.stats_mgr.register_provider(media_file_storage) @classmethod def initialize_mimetypes(cls) -> None: """Ensures that common mime-types are robust against system misconfiguration.""" mimetypes.add_type("text/html", ".html") mimetypes.add_type("application/javascript", ".js") mimetypes.add_type("application/javascript", ".mjs") mimetypes.add_type("text/css", ".css") mimetypes.add_type("image/webp", ".webp") def __repr__(self) -> str: return util.repr_(self) @property def main_script_path(self) -> str: return self._main_script_path async def start(self) -> None: """Start the server. When this returns, Streamlit is ready to accept new sessions. """ _LOGGER.debug("Starting server...") app = self._create_app() start_listening(app) port = config.get_option("server.port") _LOGGER.debug("Server started on port %s", port) await self._runtime.start() @property def stopped(self) -> Awaitable[None]: """A Future that completes when the Server's run loop has exited.""" return self._runtime.stopped def _create_app(self) -> tornado.web.Application: """Create our tornado web app.""" base = config.get_option("server.baseUrlPath") routes: list[Any] = [ ( make_url_path_regex(base, STREAM_ENDPOINT), BrowserWebSocketHandler, {"runtime": self._runtime}, ), ( make_url_path_regex(base, HEALTH_ENDPOINT), HealthHandler, {"callback": lambda: self._runtime.is_ready_for_browser_connection}, ), ( make_url_path_regex(base, METRIC_ENDPOINT), StatsRequestHandler, {"stats_manager": self._runtime.stats_mgr}, ), ( make_url_path_regex(base, HOST_CONFIG_ENDPOINT), HostConfigHandler, ), ( make_url_path_regex( base, rf"{UPLOAD_FILE_ENDPOINT}/(?P<session_id>[^/]+)/(?P<file_id>[^/]+)", ), UploadFileRequestHandler, { "file_mgr": self._runtime.uploaded_file_mgr, "is_active_session": self._runtime.is_active_session, }, ), ( make_url_path_regex(base, f"{MEDIA_ENDPOINT}/(.*)"), MediaFileHandler, {"path": ""}, ), ( make_url_path_regex(base, f"{COMPONENT_ENDPOINT}/(.*)"), ComponentRequestHandler, {"registry": self._runtime.component_registry}, ), ( make_url_path_regex(base, f"{BIDI_COMPONENT_ENDPOINT}/(.*)"), BidiComponentRequestHandler, {"component_manager": self._runtime.bidi_component_registry}, ), ] if config.get_option("server.scriptHealthCheckEnabled"): routes.extend( [ ( make_url_path_regex(base, SCRIPT_HEALTH_CHECK_ENDPOINT), HealthHandler, { "callback": lambda: self._runtime.does_script_run_without_error() }, ) ] ) if config.get_option("server.enableStaticServing"): routes.extend( [ ( make_url_path_regex(base, f"{STATIC_SERVING_ENDPOINT}/(.*)"), AppStaticFileHandler, {"path": file_util.get_app_static_dir(self.main_script_path)}, ), ] ) if is_authlib_installed(): from streamlit.web.server.oauth_authlib_routes import ( AuthCallbackHandler, AuthLoginHandler, AuthLogoutHandler, ) routes.extend( [ ( make_url_path_regex(base, OAUTH2_CALLBACK_ENDPOINT), AuthCallbackHandler, {"base_url": base}, ), ( make_url_path_regex(base, AUTH_LOGIN_ENDPOINT), AuthLoginHandler, {"base_url": base}, ), ( make_url_path_regex(base, AUTH_LOGOUT_ENDPOINT), AuthLogoutHandler, {"base_url": base}, ), ] ) if config.get_option("global.developmentMode"): _LOGGER.debug("Serving static content from the Node dev server") else: static_path = file_util.get_static_dir() _LOGGER.debug("Serving static content from %s", static_path) routes.extend( [ ( # We want to remove paths with a trailing slash, but if the path # starts with a double slash //, the redirect will point # the browser to the wrong host. make_url_path_regex( base, "(?!/)(.*)", trailing_slash="required" ), RemoveSlashHandler, ), ( make_url_path_regex(base, "(.*)"), StaticFileHandler, { "path": f"{static_path}/", "default_filename": "index.html", "reserved_paths": [ # These paths are required for identifying # the base url path. NEW_HEALTH_ENDPOINT, HOST_CONFIG_ENDPOINT, ], }, ), ( make_url_path_regex(base, trailing_slash="prohibited"), AddSlashHandler, ), ] ) return tornado.web.Application( routes, cookie_secret=get_cookie_secret(), xsrf_cookies=is_xsrf_enabled(), # Set the websocket message size. The default value is too low. websocket_max_message_size=get_max_message_size_bytes(), **get_tornado_settings(), ) @property def browser_is_connected(self) -> bool: return self._runtime.state == RuntimeState.ONE_OR_MORE_SESSIONS_CONNECTED @property def is_running_hello(self) -> bool: from streamlit.hello import streamlit_app return self._main_script_path == streamlit_app.__file__ def stop(self) -> None: cli_util.print_to_cli(" Stopping...", fg="blue") self._runtime.stop() def _set_tornado_log_levels() -> None: if not config.get_option("global.developmentMode"): # Hide logs unless they're super important. # Example of stuff we don't care about: 404 about .js.map files. logging.getLogger("tornado.access").setLevel(logging.ERROR) logging.getLogger("tornado.application").setLevel(logging.ERROR) logging.getLogger("tornado.general").setLevel(logging.ERROR)
0
hf_public_repos/streamlit/lib/streamlit/web
hf_public_repos/streamlit/lib/streamlit/web/server/websocket_headers.py
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations from streamlit import runtime from streamlit.deprecation_util import show_deprecation_warning from streamlit.runtime.metrics_util import gather_metrics from streamlit.runtime.scriptrunner_utils.script_run_context import get_script_run_ctx from streamlit.web.server.browser_websocket_handler import BrowserWebSocketHandler _GET_WEBSOCKET_HEADERS_DEPRECATE_MSG = ( "The `_get_websocket_headers` function is deprecated and will be removed " "in a future version of Streamlit. Please use `st.context.headers` instead." ) @gather_metrics("_get_websocket_headers") def _get_websocket_headers() -> dict[str, str] | None: """Return a copy of the HTTP request headers for the current session's WebSocket connection. If there's no active session, return None instead. Raise an error if the server is not running. Note to the intrepid: this is an UNSUPPORTED, INTERNAL API. (We don't have plans to remove it without a replacement, but we don't consider this a production-ready function, and its signature may change without a deprecation warning.) """ show_deprecation_warning(_GET_WEBSOCKET_HEADERS_DEPRECATE_MSG) ctx = get_script_run_ctx() if ctx is None: return None session_client = runtime.get_instance().get_client(ctx.session_id) if session_client is None: return None if not isinstance(session_client, BrowserWebSocketHandler): raise TypeError( f"SessionClient is not a BrowserWebSocketHandler! ({session_client})" ) return dict(session_client.request.headers)
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1