o
    Zh <                     @  s&  d dl mZ d dlmZmZmZ d dlmZ d dlm	Z	 d dl
mZmZmZmZ d dlmZ d dlmZmZ d dlmZ d d	lmZ d d
lmZ er^d dlmZ d dlmZmZ d dlm Z  dddZ!ed ddZ"G dd deZ#G dd dee$e$f Z%G dd dee$e$f Z&G dd dZ'dS )!    )annotations)IterableIteratorMapping)	lru_cache)MappingProxyType)TYPE_CHECKINGAnyLiteralcast)runtime)maybe_add_page_pathmaybe_trim_page_path)gather_metrics)get_script_run_ctx)AttributeDictionary)Morsel)HTTPHeadersHTTPServerRequest)RequestHandlerreturnHTTPServerRequest | Nonec                  C  s\   t  } | d u r	d S t | j}|d u rd S t|j dt|j dkr(d S td|j	S )N.zFstreamlit.web.server.browser_websocket_handler.BrowserWebSocketHandlerr   )
r   r   get_instance
get_client
session_idtype
__module____qualname__r   request)ctxsession_client r"   Z/var/www/html/Persson_Maskin/env/lib/python3.10/site-packages/streamlit/runtime/context.py_get_request#   s   r$   namestrc                 C  s   d dd | dD S )ziMap a header name to Http-Header-Case.

    >>> _normalize_header("coNtent-TYPE")
    'Content-Type'
    -c                 s  s    | ]}|  V  qd S N)
capitalize).0wr"   r"   r#   	<genexpr>@   s    z$_normalize_header.<locals>.<genexpr>)joinsplit)r%   r"   r"   r#   _normalize_header9   s   r/   c                      s:   e Zd ZU dZded< d fddZedd
dZ  ZS )StreamlitThemea  A dictionary-like object containing theme information.

    This class extends the functionality of a standard dictionary to allow items
    to be accessed via attribute-style dot notation in addition to the traditional
    key-based access. If a dictionary item is accessed and is itself a dictionary,
    it is automatically wrapped in another `AttributeDictionary`, enabling recursive
    attribute-style access.
    zLiteral['dark', 'light'] | Noner   
theme_infodict[str, str | None]c                   s   t  | d S r(   )super__init__)selfr1   	__class__r"   r#   r4   O   s   zStreamlitTheme.__init__context_dictr   c                 C  s   | |S r(   r"   )clsr8   r"   r"   r#   from_context_infoR   s   z StreamlitTheme.from_context_info)r1   r2   )r8   r2   r   r0   )	__name__r   r   __doc____annotations__r4   classmethodr:   __classcell__r"   r"   r6   r#   r0   C   s   
 	r0   c                   @  sV   e Zd ZdddZedd	d
ZdddZdddZd ddZd!ddZ	d"ddZ
dS )#StreamlitHeadersheadersIterable[tuple[str, str]]r   Nonec                 C  s6   i }|D ]\}}| t|g }|| q|| _d S r(   )
setdefaultr/   append_headers)r5   rA   dict_like_headerskeyvalueheader_valuer"   r"   r#   r4   X   s
   
zStreamlitHeaders.__init__tornado_headersr   c                 C  s   | |  S r(   )get_all)r9   rK   r"   r"   r#   from_tornado_headersa   s   z%StreamlitHeaders.from_tornado_headersrH   r&   	list[str]c                 C  s   t | jt|g S r(   )listrF   getr/   r5   rH   r"   r"   r#   rL   e   s   zStreamlitHeaders.get_allc                 C  s.   z
| j t| d W S  ty   t|d w )Nr   )rF   r/   LookupErrorKeyErrorrQ   r"   r"   r#   __getitem__h   s
   
zStreamlitHeaders.__getitem__intc                 C  
   t | jS z,Number of unique headers present in request.)lenrF   r5   r"   r"   r#   __len__n      
zStreamlitHeaders.__len__Iterator[str]c                 C  rV   r(   )iterrF   rY   r"   r"   r#   __iter__r      
zStreamlitHeaders.__iter__dict[str, str]c                   s    fdd D S )Nc                   s   i | ]}| | qS r"   r"   )r*   rH   rY   r"   r#   
<dictcomp>v   s    z,StreamlitHeaders.to_dict.<locals>.<dictcomp>r"   rY   r"   rY   r#   to_dictu   s   zStreamlitHeaders.to_dictN)rA   rB   r   rC   )rK   r   r   r@   )rH   r&   r   rN   rH   r&   r   r&   r   rU   r   r\   r   r`   )r;   r   r   r4   r>   rM   rL   rT   rZ   r^   rb   r"   r"   r"   r#   r@   W   s    
	



r@   c                   @  sL   e Zd ZdddZedd	d
ZdddZdddZdddZdddZ	dS )StreamlitCookiescookiesMapping[str, str]r   rC   c                 C  s   t || _d S r(   )r   _cookies)r5   rh   r"   r"   r#   r4   z   s   zStreamlitCookies.__init__tornado_cookiesdict[str, Morsel[Any]]c                 C  s(   i }|  D ]	\}}|j||< q| |S r(   )itemsrI   )r9   rk   dict_like_cookiesrH   morselr"   r"   r#   from_tornado_cookies}   s   z%StreamlitCookies.from_tornado_cookiesrH   r&   c                 C  s
   | j | S r(   )rj   rQ   r"   r"   r#   rT      r_   zStreamlitCookies.__getitem__rU   c                 C  rV   rW   )rX   rj   rY   r"   r"   r#   rZ      r[   zStreamlitCookies.__len__r\   c                 C  rV   r(   )r]   rj   rY   r"   r"   r#   r^      r_   zStreamlitCookies.__iter__r`   c                 C  rV   r(   )dictrj   rY   r"   r"   r#   rb      r_   zStreamlitCookies.to_dictN)rh   ri   r   rC   )rk   rl   r   rg   rc   rd   re   rf   )
r;   r   r   r4   r>   rp   rT   rZ   r^   rb   r"   r"   r"   r#   rg   y   s    



rg   c                   @  s   e Zd ZdZeedd%ddZeedd&d	d
Zeedd'ddZeedd(ddZ	eedd)ddZ
eedd(ddZeedd(ddZeedd(ddZeed d*d"d#Zd$S )+ContextProxya  An interface to access user session context.

    ``st.context`` provides a read-only interface to access headers and cookies
    for the current user session.

    Each property (``st.context.headers`` and ``st.context.cookies``) returns
    a dictionary of named values.

    zcontext.headersr   r@   c                 C  s"   t  }|du rti S t|jS )a  A read-only, dict-like object containing headers sent in the initial request.

        Keys are case-insensitive and may be repeated. When keys are repeated,
        dict-like methods will only return the last instance of each key. Use
        ``.get_all(key="your_repeated_key")`` to see all values if the same
        header is set multiple times.

        Examples
        --------
        **Example 1: Access all available headers**

        Show a dictionary of headers (with only the last instance of any
        repeated key):

        >>> import streamlit as st
        >>>
        >>> st.context.headers

        **Example 2: Access a specific header**

        Show the value of a specific header (or the last instance if it's
        repeated):

        >>> import streamlit as st
        >>>
        >>> st.context.headers["host"]

        Show of list of all headers for a given key:

        >>> import streamlit as st
        >>>
        >>> st.context.headers.get_all("pragma")

        N)r$   r@   rM   rA   )r5   session_client_requestr"   r"   r#   rA      s   'zContextProxy.headerszcontext.cookiesrg   c                 C  s&   t  }|du rti S |j}t|S )a  A read-only, dict-like object containing cookies sent in the initial request.

        Examples
        --------
        **Example 1: Access all available cookies**

        Show a dictionary of cookies:

        >>> import streamlit as st
        >>>
        >>> st.context.cookies

        **Example 2: Access a specific cookie**

        Show the value of a specific cookie:

        >>> import streamlit as st
        >>>
        >>> st.context.cookies["_ga"]

        N)r$   rg   rh   rp   )r5   rs   rh   r"   r"   r#   rh      s
   
zContextProxy.cookieszcontext.themer0   c                 C  s6   t  }|du s|jdu rtddiS td|jjiS )a8  A read-only, dictionary-like object containing theme information.

        Theme information is restricted to the ``type`` of the theme (dark or
        light) and is inferred from the background color of the app.

        .. note::
            Changes made to the background color through CSS are not included.
            Additionally, the theme type may be incorrect during a change in
            theme, like in the following situations:

            - When the app is first loaded within a session
            - When the user changes the theme in the settings menu

            For more information and to upvote an improvement, see GitHub issue
            `#11920 <https://github.com/streamlit/streamlit/issues/11920>`_.

        Attributes
        ----------
        type : "light", "dark"
            The theme type inferred from the background color of the app.

        Example
        -------
        Access the theme type of the app:

        >>> import streamlit as st
        >>>
        >>> st.write(f"The current theme type is {st.context.theme.type}.")

        Nr   )r   context_infor0   r:   color_schemer5   r    r"   r"   r#   theme   s   !zContextProxy.themezcontext.timezone
str | Nonec                 C  $   t  }|du s|jdu rdS |jjS )aF  The read-only timezone of the user's browser.

        Example
        -------
        Access the user's timezone, and format a datetime to display locally:

        >>> import streamlit as st
        >>> from datetime import datetime, timezone
        >>> import pytz
        >>>
        >>> tz = st.context.timezone
        >>> tz_obj = pytz.timezone(tz)
        >>>
        >>> now = datetime.now(timezone.utc)
        >>>
        >>> f"The user's timezone is {tz}."
        >>> f"The UTC time is {now}."
        >>> f"The user's local time is {now.astimezone(tz_obj)}"

        N)r   rt   timezonerv   r"   r"   r#   rz     s   zContextProxy.timezonezcontext.timezone_offset
int | Nonec                 C  ry   )ac  The read-only timezone offset of the user's browser.

        Example
        -------
        Access the user's timezone offset, and format a datetime to display locally:

        >>> import streamlit as st
        >>> from datetime import datetime, timezone, timedelta
        >>>
        >>> tzoff = st.context.timezone_offset
        >>> tz_obj = timezone(-timedelta(minutes=tzoff))
        >>>
        >>> now = datetime.now(timezone.utc)
        >>>
        >>> f"The user's timezone is {tz}."
        >>> f"The UTC time is {now}."
        >>> f"The user's local time is {now.astimezone(tz_obj)}"

        N)r   rt   timezone_offsetrv   r"   r"   r#   r|   4     zContextProxy.timezone_offsetzcontext.localec                 C  ry   )a  The read-only locale of the user's browser.

        ``st.context.locale`` returns the value of |navigator.language|_ from
        the user's DOM. This is a string representing the user's preferred
        language (e.g. "en-US").

        .. |navigator.language| replace:: ``navigator.language``
        .. _navigator.language: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/language

        Example
        -------
        Access the user's locale to display locally:

        >>> import streamlit as st
        >>>
        >>> if st.context.locale == "fr-FR":
        >>>     st.write("Bonjour!")
        >>> else:
        >>>     st.write("Hello!")

        N)r   rt   localerv   r"   r"   r#   r~   O  s   zContextProxy.localezcontext.urlc                 C  s<   t  }|du s|jdu rdS |jj}t||j}t||jS )as  The read-only URL of the app in the user's browser.

        ``st.context.url`` returns the URL through which the user is accessing
        the app. This includes the scheme, domain name, port, and path. If
        query parameters or anchors are present in the URL, they are removed
        and not included in this value.

        Example
        -------
        Conditionally show content when you access your app through
        ``localhost``:

        >>> import streamlit as st
        >>>
        >>> if st.context.url.startswith("http://localhost"):
        >>>     st.write("You are running the app locally.")
        N)r   rt   urlr   pages_managerr   )r5   r    url_from_frontendurl_without_page_prefixr"   r"   r#   r   l  s   zContextProxy.urlzcontext.ip_addressc                 C  s(   t  }|dur|j}|dv rdS |S dS )aI  The read-only IP address of the user's connection.

        This should not be used for security measures because it can easily be
        spoofed. When a user accesses the app through ``localhost``, the IP
        address is ``None``. Otherwise, the IP address is determined from the
        |remote_ip|_ attribute of the Tornado request object and may be an
        IPv4 or IPv6 address.

        .. |remote_ip| replace:: ``remote_ip``
        .. _remote_ip: https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest.remote_ip

        Example
        -------
        Check if the user has an IPv4 or IPv6 address:

        >>> import streamlit as st
        >>>
        >>> ip = st.context.ip_address
        >>> if ip is None:
        >>>     st.write("No IP address. This is expected in local development.")
        >>> elif ip.contains(":"):
        >>>     st.write("You have an IPv6 address.")
        >>> elif ip.contains("."):
        >>>     st.write("You have an IPv4 address.")
        >>> else:
        >>>     st.error("This should not happen.")
        N>   ::1	127.0.0.1)r$   	remote_ip)r5   rs   r   r"   r"   r#   
ip_address  s   zContextProxy.ip_addresszcontext.is_embeddedbool | Nonec                 C  ry   )a  Whether the app is embedded.

        This property returns a boolean value indicating whether the app is
        running in an embedded context. This is determined by the presence of
        ``embed=true`` as a query parameter in the URL. This is the only way to
        determine if the app is currently configured for embedding because
        embedding settings are not accessible through ``st.query_params`` or
        ``st.context.url``.

        Example
        -------
        Conditionally show content when the app is running in an embedded
        context:

        >>> import streamlit as st
        >>>
        >>> if st.context.is_embedded:
        >>>     st.write("You are running the app in an embedded context.")
        N)r   rt   is_embeddedrv   r"   r"   r#   r     r}   zContextProxy.is_embeddedN)r   r@   )r   rg   )r   r0   )r   rx   )r   r{   )r   r   )r;   r   r   r<   propertyr   rA   rh   rw   rz   r|   r~   r   r   r   r"   r"   r"   r#   rr      s:    
, &$rr   N)r   r   )r%   r&   r   r&   )(
__future__r   collections.abcr   r   r   	functoolsr   typesr   typingr   r	   r
   r   	streamlitr   streamlit.runtime.context_utilr   r   streamlit.runtime.metrics_utilr   7streamlit.runtime.scriptrunner_utils.script_run_contextr   streamlit.utilr   http.cookiesr   tornado.httputilr   r   tornado.webr   r$   r/   r0   r&   r@   rg   rr   r"   r"   r"   r#   <module>   s*   
	"