コード例 #1
0
def _check_conflicts():
    # Node-related conflicts

    # When using the Node server, we must always connect to 8501 (this is
    # hard-coded in JS). Otherwise, the browser would decide what port to
    # connect to based on either:
    #   1. window.location.port, which in dev is going to be (3000)
    #   2. the serverPort value in manifest.json, which would work, but only
    #   exists with server.liveSave.

    # Import logger locally to prevent circular references
    from streamlit.logger import get_logger

    LOGGER = get_logger(__name__)

    if get_option("global.developmentMode"):
        assert _is_unset(
            "server.port"
        ), "server.port does not work when global.developmentMode is true."

        assert _is_unset("browser.serverPort"), (
            "browser.serverPort does not work when global.developmentMode is "
            "true.")

    # Sharing-related conflicts

    if get_option("global.sharingMode") == "s3":
        assert is_manually_set("s3.bucket"), (
            'When global.sharingMode is set to "s3", '
            "s3.bucket must also be set")
        both_are_set = is_manually_set("s3.accessKeyId") and is_manually_set(
            "s3.secretAccessKey")
        both_are_unset = _is_unset("s3.accessKeyId") and _is_unset(
            "s3.secretAccessKey")
        assert both_are_set or both_are_unset, (
            "In config.toml, s3.accessKeyId and s3.secretAccessKey must "
            "either both be set or both be unset.")

        if is_manually_set("s3.url"):
            # If s3.url is set, ensure that it's an absolute URL.
            # An absolute URL starts with either `scheme://` or `//` --
            # if the configured URL does not start with either prefix,
            # prepend it with `//` to make it absolute. (If we don't do this,
            # and the user enters something like `url=myhost.com/reports`, the
            # browser will assume this is a relative URL, and will prepend
            # the hostname of the Streamlit instance to the configured URL.)
            s3_url = get_option("s3.url")
            parsed = urllib.parse.urlparse(s3_url)
            if parsed.netloc == "":
                _set_option("s3.url", "//" + s3_url,
                            get_where_defined("s3.url"))

    elif get_option("global.sharingMode"
                    ) == "file" and not get_option("global.developmentMode"):
        # Warn users that "sharingMode=file" probably isn't what they meant
        # to do.
        LOGGER.warning(
            "'sharingMode' is set to 'file', but Streamlit is not configured "
            "for development. This sharingMode is used for debugging "
            "Streamlit itself, and is not supported for other use-cases. "
            "\n\nTo remove this warning, set the 'sharingMode' option to "
            "another value, or remove it from your Streamlit config.")

    # XSRF conflicts
    if get_option("server.enableXsrfProtection"):
        if not get_option("server.enableCORS") or get_option(
                "global.developmentMode"):
            LOGGER.warning("""
Warning: the config option 'server.enableCORS=false' is not compatible with 'server.enableXsrfProtection=true'.
As a result, 'server.enableCORS' is being overridden to 'true'.

More information:
In order to protect against CSRF attacks, we send a cookie with each request.
To do so, we must specify allowable origins, which places a restriction on
cross-origin resource sharing.

If cross origin resource sharing is required, please disable server.enableXsrfProtection.
            """)
コード例 #2
0
import botocore
import logging
import math
import mimetypes
import os

from tornado import gen
from tornado.concurrent import run_on_executor, futures

from streamlit import errors
from streamlit import config
from streamlit.storage.abstract_storage import AbstractStorage

from streamlit.logger import get_logger

LOGGER = get_logger(__name__)


class S3Storage(AbstractStorage):
    """Class to handle S3 uploads."""

    executor = futures.ThreadPoolExecutor(5)

    def __init__(self):
        """Constructor."""
        super(S3Storage, self).__init__()

        # For now don't enable verbose boto logs
        # TODO(armando): Make this configurable.
        log = logging.getLogger("botocore")
        log.propagate = False
コード例 #3
0
ファイル: config_option.py プロジェクト: jbroch1/Project1
    def set_value(self, value, where_defined=None):
        """Set the value of this option.

        Parameters
        ----------
        value
            The new value for this parameter.
        where_defined : str
            New value to remember where this parameter was set.

        """
        self._get_val_func = lambda: value

        if where_defined is None:
            self.where_defined = ConfigOption.DEFAULT_DEFINITION
        else:
            self.where_defined = where_defined

        if self.deprecated and self.where_defined != ConfigOption.DEFAULT_DEFINITION:

            details = {
                "key": self.key,
                "file": self.where_defined,
                "explanation": self.deprecation_text,
                "date": self.expiration_date,
            }

            if self.is_expired():
                raise DeprecationError(
                    textwrap.dedent(
                        """
                    ════════════════════════════════════════════════
                    %(key)s IS NO LONGER SUPPORTED.

                    %(explanation)s

                    Please update %(file)s.
                    ════════════════════════════════════════════════
                    """
                    )
                    % details
                )
            else:
                from streamlit.logger import get_logger

                LOGGER = get_logger(__name__)
                LOGGER.warning(
                    textwrap.dedent(
                        """
                    ════════════════════════════════════════════════
                    %(key)s IS DEPRECATED.
                    %(explanation)s

                    This option will be removed on or after %(date)s.

                    Please update %(file)s.
                    ════════════════════════════════════════════════
                    """
                    )
                    % details
                )
コード例 #4
0
For more detailed info, see https://docs.streamlit.io.
"""

# IMPORTANT: Prefix with an underscore anything that the user shouldn't see.

# NOTE: You'll see lots of "noqa: F821" in this file. That's because we
# manually mess with the local namespace so the linter can't know that some
# identifiers actually exist in the namespace.

# Must be at the top, to avoid circular dependency.
from streamlit import logger as _logger
from streamlit import config as _config
from streamlit.proto.RootContainer_pb2 import RootContainer
from streamlit.secrets import Secrets, SECRETS_FILE_LOC

_LOGGER = _logger.get_logger("root")

# Give the package a version.
import pkg_resources as _pkg_resources
from typing import List

# This used to be pkg_resources.require('streamlit') but it would cause
# pex files to fail. See #394 for more details.
__version__ = _pkg_resources.get_distribution("streamlit").version

import contextlib as _contextlib
import re as _re
import sys as _sys
import textwrap as _textwrap
import threading as _threading
import traceback as _traceback
コード例 #5
0
import json
import os

import streamlit as st
from streamlit.logger import get_logger
from PIL import Image

from butt_or_bread.core import ButtBreadClassifier
from butt_or_bread.utils import health_check

# Create Streamlit logger
st_logger = get_logger(__name__)
st.set_option("deprecation.showfileUploaderEncoding", False)

# Load Streamlit configuration file
with open("streamlit_app.json") as cfg_file:
    st_app_cfg = json.load(cfg_file)

ui_cfg = st_app_cfg["ui"]
model_cfg = st_app_cfg["model"]
image_cfg = st_app_cfg["image"]

st.set_page_config(
    layout="centered",
    page_title=ui_cfg["title"],
    page_icon=ui_cfg["icon"],
)


@st.cache(allow_output_mutation=True,
          suppress_st_warning=True,
コード例 #6
0
ファイル: config.py プロジェクト: astrojams1/cleanstreets
def get_config_options(
    force_reparse=False,
    options_from_flags: Optional[Dict[str, Any]] = None
) -> Dict[str, ConfigOption]:
    """Create and return a dict mapping config option names to their values,
    returning a cached dict if possible.

    Config option values are sourced from the following locations. Values
    set in locations further down the list overwrite those set earlier.
      1. default values defined in this file
      2. the global `~/.streamlit/config.toml` file
      3. per-project `$CWD/.streamlit/config.toml` files
      4. environment variables such as `STREAMLIT_SERVER_PORT`
      5. command line flags passed to `streamlit run`

    Parameters
    ----------
    force_reparse : bool
        Force config files to be parsed so that we pick up any changes to them.

    options_from_flags : Optional[Dict[str, any]
        Config options that we received via CLI flag.

    Returns
    ----------
    Dict[str, ConfigOption]
        An ordered dict that maps config option names to their values.
    """
    global _config_options

    if not options_from_flags:
        options_from_flags = {}

    # Avoid grabbing the lock in the case where there's nothing for us to do.
    config_options = _config_options
    if config_options and not force_reparse:
        return config_options

    with _config_lock:
        # Short-circuit if config files were parsed while we were waiting on
        # the lock.
        if _config_options and not force_reparse:
            return _config_options

        old_options = _config_options
        _config_options = copy.deepcopy(_config_options_template)

        # Values set in files later in the CONFIG_FILENAMES list overwrite those
        # set earlier.
        for filename in CONFIG_FILENAMES:
            if not os.path.exists(filename):
                continue

            with open(filename, "r", encoding="utf-8") as input:
                file_contents = input.read()

            _update_config_with_toml(file_contents, filename)

        for opt_name, opt_val in options_from_flags.items():
            _set_option(opt_name, opt_val, _DEFINED_BY_FLAG)

        if old_options and config_util.server_option_changed(
                old_options, _config_options):
            # Import logger locally to prevent circular references.
            from streamlit.logger import get_logger

            LOGGER = get_logger(__name__)
            LOGGER.warning(
                "An update to the [server] config option section was detected."
                " To have these changes be reflected, please restart streamlit."
            )

        _on_config_parsed.send()
        return _config_options
コード例 #7
0
ファイル: session_state.py プロジェクト: davgit/streamlit
)

import attr

from pympler.asizeof import asizeof

import streamlit as st
from streamlit import logger as _logger
from streamlit.errors import StreamlitAPIException
from streamlit.proto.WidgetStates_pb2 import WidgetState as WidgetStateProto
from streamlit.proto.WidgetStates_pb2 import WidgetStates as WidgetStatesProto

if TYPE_CHECKING:
    from streamlit.server.server import SessionInfo

logger = _logger.get_logger(__name__)

GENERATED_WIDGET_KEY_PREFIX = "$$GENERATED_WIDGET_KEY"

STREAMLIT_INTERNAL_KEY_PREFIX = "$$STREAMLIT_INTERNAL_KEY"
SCRIPT_RUN_WITHOUT_ERRORS_KEY = (
    f"{STREAMLIT_INTERNAL_KEY_PREFIX}_SCRIPT_RUN_WITHOUT_ERRORS")


@attr.s(auto_attribs=True, slots=True, frozen=True)
class Serialized:
    """A widget value that's serialized to a protobuf. Immutable."""

    value: WidgetStateProto