streamlit-base-extras


Namestreamlit-base-extras JSON
Version 0.2.44 PyPI version JSON
download
home_pagehttps://github.com/blipk/streamlitextras
SummaryMake building with streamlit easier.
upload_time2023-12-07 14:32:14
maintainer
docs_urlNone
authorblipk
requires_python>=3.10
licenseMIT license
keywords streamlitextras streamlit router authenticator javascript cookie thread
VCS
bugtrack_url
requirements streamlit urllib3 requests gcloud pyjwt firebase pyrebase4 sseclient PyCryptodome requests_toolbelt firebase-admin google-cloud-storage twine Sphinx sphinx-autobuild sphinx-rtd-theme docutils sphinxcontrib-apidoc
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Streamlit Extras

These are some components and modules designed to make working with streamlit easier.

I had a project that required some of these parts, I tried some other community projects that were similar,
but none of them had the features I required, so I ended up rewriting my own implementations of them.

## Installation and Requirements

Install from PyPI with pip:
`python3 -m pip install streamlit-base-extras`

Requires Streamlit 1.23.1+ and Python 3.10+,

## The modules

#### Router
Page router with various features.

```Python
import random
import streamlit as st
from streamlitextras.router import get_router

router = None
def main():
    global router
    pages = {
        "main": main_page,
        "other": another_page,
    }
    st.set_page_config(
        page_title="MyApp",
        layout="wide",
        initial_sidebar_state="auto"
    )
    router = get_router()
    router.delayed_init()  # This is required to make sure current Router stays in session state

    computed_chance = random.randrange(10)
    if computed_chance > 1:
        router.route()
    else:
        router.route("other", computed_chance)

def main_page(page_state = None):
    st.write("This is the main.")

def another_page(page_state = None):
    st.write(f"This is another page, you're lucky to be here. Number {page_state} lucky.")

if __name__ == "__main__":
    main()
```

See the [package readme](streamlitextras/router) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.


#### Cookie Manager
Component function to manage in-browser cookies from streamlit.

```Python
import streamlit as st
from streamlitextras.cookiemanager import get_cookie_manager

cookie_manager = None
def main():
    global cookie_manager
    cookie_manager = get_cookie_manager()
    cookie_manager.delayed_init() # Makes sure CookieManager stays in st.session_state

    cookie_manager.set("my_cookie_name", "I'm a cookie!")
    my_cookie_value = cookie_manager.get("my_cookie_name")
    print(my_cookie_value) # "I'm a cookie"

    my_cookies = cookie_manager.get_all()
    print(my_cookies) # {"my_cookie_name": "I'm a cookie!"}

    cookie_manager.delete("my_cookie_name")
    my_cookie_value = cookie_manager.get("my_cookie_name")
    print(my_cookie_value) # None


if __name__ == "__main__":
    main()
```

See the [package readme](streamlitextras/cookiemanager) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.


#### Authenticator
Authentication module that creates streamlit register/login forms, and uses firebase auth to register and manage users.
Can also be inherited to use a custom authentication provider.

```Python
import streamlit as st
from streamlitextras.authenticator import get_auth

auth = None
def main():
    global auth
    auth = get_auth("my_cookie_name")
    auth.delayed_init() # This is required to make sure current Authenticator stays in session state

    auth_status = auth.auth_status
    user = auth.current_user

    if auth_status and user:
        st.write(f"Welcome {user.displayName}!")
    else:
        auth_page()

def auth_page():
    info_box = st.container()

    if auth.current_form == "login" or not auth.current_form:
        user, res, error = auth.login("Login")
    if auth.current_form == "register":
        res, error = auth.register_user("Register")
    elif auth.current_form == "reset_password":
        res, error = auth.reset_password("Request password change email")

    if res:
        info_box.info("Success!")

    if error:
        info_box.error(error.message)

if __name__ == "__main__":
    main()

```

See the [package readme](streamlitextras/authenticator) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.


#### Threader
Makes spawning and working with `threading.Threads` with streamlit easy.

```Python
import time
import streamlit as st
import reruntrigger_default # This is required so the watcher can rerun from this file
from streamlitextras.threader import lock, trigger_rerun, \
                                     streamlit_thread, get_thread, \
                                     last_trigger_time

def main():
    thread_name = streamlit_thread(my_threaded_function, (5,))
    st.write("This should be here before my_threaded_function() is done!")
    st.button("Thread info", on_click=button_callback, args=(thread_name,))

def button_callback(thread_name):
    # Sometimes streamlit will trigger button callbacks when re-running,
    # So we block them if we triggered a rerun recently
    if last_trigger_time() < 1:
        return
    my_thread = get_thread(thread_name)
    st.write(my_thread) # threading.Thread

def my_threaded_function(time):
    time.sleep(time)
    with lock:
        # Do something that might interfere with other threads,
        # file operations or setting st.session_state
        pass
    print(f"Thread done! I slept for {time} seconds.")

if __name__ == "__main__":
    main()
```

See the [package readme](streamlitextras/threader) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.


#### Logger
Implementation of Loguru set up to work well with this package.

```Python
import streamlit as st
from streamlitextras.logger import log

def main():
    log.debug("My app just started!")
    st.write("My app")

if __name__ == "__main__":
    main()
```

See the [package readme](streamlitextras/logger) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.


#### Other helpers
See the [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for a full list of functions and their usage in these files.

###### streamlitextras.webutils
Some utility functions to run javascript, wrappers around various javascript routines,
and some other browser related formatting utilities.

```Python
import streamlit as st
from streamlitextras.webutils import stxs_javascript, get_user_timezone, \
                                    bytes_to_data_uri, trigger_download

def main():
    # Returns tz database name can be used with pytz and datetime
    timezone = get_user_timezone()
    continent, city = timezone.split("/")
    stxs_javascript(f"""alert("Hello person from {city}! Welcome to my streamlit app.");"""

    uploaded_file = st.file_uploader("Upload a file")

    if uploaded_file:
        data_uri = bytes_to_data_uri(uploaded_file)
        # Browser will prompt to save the file
        trigger_download(data_uri, "The file you just uploaded.renamed")

if __name__ == "__main__":
    main()
```

See the [source code](streamlitextras/webutils.py).

###### streamlitextras.helpers
Class implementation that streamlines creating basic HTML elements with st.markdown,
and some other useful functions.

See the [source code](streamlitextras/helpers.py).

###### streamlitextras.storageservice
Helper to interact with Google Cloud Storage with a service worker account.

It has some basic wrapper functions to use the service account to manage buckets and blobs,
as well as computing hashes from Python bytes objects that match gcloud blobs.

See the [source code](streamlitextras/storageservice.py) and the [google python api reference](https://googleapis.dev/python/storage/latest/) for more.

```Python
import streamlitextras.storageservice as storageservice

with open("my.file", "rb") as f:
    computed_md5_hash = storageservice.compute_bytes_md5hash(f.read())

buckets = storageservice.get_buckets() # Returns an iterable
list_buckets = []
for bucket in buckets:
    list_buckets.append(buckets)
buckets = list_buckets

blobs = get_blobs(buckets[0].name) # Returns an iterable
list_blobs = p[]
for blob in blobs:
    list_blobs.append(blob)
blobs = list_blobs

my_file_blob = blobs[0] # my.file

assert my_file_blob.md5_hash == computed_md5_hash # True
```

You will need to set up a service worker on your google cloud project or firebase project,
and add the details from its .json key to `.streamlit/secrets.toml`

```TOML
[gcp_service_account]
type = ""
project_id = ""
private_key_id = ""
private_key = ""
client_email = ""
client_id = ""
auth_uri = ""
token_uri = ""
auth_provider_x509_cert_url = ""
client_x509_cert_url = ""
```

###### streamlitextras.utils
Some utility functions for Python development.

See the [source code](streamlitextras/utils.py).

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/blipk/streamlitextras",
    "name": "streamlit-base-extras",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": "",
    "keywords": "streamlitextras,streamlit,router,authenticator,javascript,cookie,thread",
    "author": "blipk",
    "author_email": "blipk+@github.com",
    "download_url": "https://files.pythonhosted.org/packages/74/82/b7494906018ad629807aa89b9bf7eb0b8ab5ceb37ea80f125642ede47bfc/streamlit-base-extras-0.2.44.tar.gz",
    "platform": null,
    "description": "# Streamlit Extras\n\nThese are some components and modules designed to make working with streamlit easier.\n\nI had a project that required some of these parts, I tried some other community projects that were similar,\nbut none of them had the features I required, so I ended up rewriting my own implementations of them.\n\n## Installation and Requirements\n\nInstall from PyPI with pip:\n`python3 -m pip install streamlit-base-extras`\n\nRequires Streamlit 1.23.1+ and Python 3.10+,\n\n## The modules\n\n#### Router\nPage router with various features.\n\n```Python\nimport random\nimport streamlit as st\nfrom streamlitextras.router import get_router\n\nrouter = None\ndef main():\n    global router\n    pages = {\n        \"main\": main_page,\n        \"other\": another_page,\n    }\n    st.set_page_config(\n        page_title=\"MyApp\",\n        layout=\"wide\",\n        initial_sidebar_state=\"auto\"\n    )\n    router = get_router()\n    router.delayed_init()  # This is required to make sure current Router stays in session state\n\n    computed_chance = random.randrange(10)\n    if computed_chance > 1:\n        router.route()\n    else:\n        router.route(\"other\", computed_chance)\n\ndef main_page(page_state = None):\n    st.write(\"This is the main.\")\n\ndef another_page(page_state = None):\n    st.write(f\"This is another page, you're lucky to be here. Number {page_state} lucky.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSee the [package readme](streamlitextras/router) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.\n\n\n#### Cookie Manager\nComponent function to manage in-browser cookies from streamlit.\n\n```Python\nimport streamlit as st\nfrom streamlitextras.cookiemanager import get_cookie_manager\n\ncookie_manager = None\ndef main():\n    global cookie_manager\n    cookie_manager = get_cookie_manager()\n    cookie_manager.delayed_init() # Makes sure CookieManager stays in st.session_state\n\n    cookie_manager.set(\"my_cookie_name\", \"I'm a cookie!\")\n    my_cookie_value = cookie_manager.get(\"my_cookie_name\")\n    print(my_cookie_value) # \"I'm a cookie\"\n\n    my_cookies = cookie_manager.get_all()\n    print(my_cookies) # {\"my_cookie_name\": \"I'm a cookie!\"}\n\n    cookie_manager.delete(\"my_cookie_name\")\n    my_cookie_value = cookie_manager.get(\"my_cookie_name\")\n    print(my_cookie_value) # None\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSee the [package readme](streamlitextras/cookiemanager) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.\n\n\n#### Authenticator\nAuthentication module that creates streamlit register/login forms, and uses firebase auth to register and manage users.\nCan also be inherited to use a custom authentication provider.\n\n```Python\nimport streamlit as st\nfrom streamlitextras.authenticator import get_auth\n\nauth = None\ndef main():\n    global auth\n    auth = get_auth(\"my_cookie_name\")\n    auth.delayed_init() # This is required to make sure current Authenticator stays in session state\n\n    auth_status = auth.auth_status\n    user = auth.current_user\n\n    if auth_status and user:\n        st.write(f\"Welcome {user.displayName}!\")\n    else:\n        auth_page()\n\ndef auth_page():\n    info_box = st.container()\n\n    if auth.current_form == \"login\" or not auth.current_form:\n        user, res, error = auth.login(\"Login\")\n    if auth.current_form == \"register\":\n        res, error = auth.register_user(\"Register\")\n    elif auth.current_form == \"reset_password\":\n        res, error = auth.reset_password(\"Request password change email\")\n\n    if res:\n        info_box.info(\"Success!\")\n\n    if error:\n        info_box.error(error.message)\n\nif __name__ == \"__main__\":\n    main()\n\n```\n\nSee the [package readme](streamlitextras/authenticator) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.\n\n\n#### Threader\nMakes spawning and working with `threading.Threads` with streamlit easy.\n\n```Python\nimport time\nimport streamlit as st\nimport reruntrigger_default # This is required so the watcher can rerun from this file\nfrom streamlitextras.threader import lock, trigger_rerun, \\\n                                     streamlit_thread, get_thread, \\\n                                     last_trigger_time\n\ndef main():\n    thread_name = streamlit_thread(my_threaded_function, (5,))\n    st.write(\"This should be here before my_threaded_function() is done!\")\n    st.button(\"Thread info\", on_click=button_callback, args=(thread_name,))\n\ndef button_callback(thread_name):\n    # Sometimes streamlit will trigger button callbacks when re-running,\n    # So we block them if we triggered a rerun recently\n    if last_trigger_time() < 1:\n        return\n    my_thread = get_thread(thread_name)\n    st.write(my_thread) # threading.Thread\n\ndef my_threaded_function(time):\n    time.sleep(time)\n    with lock:\n        # Do something that might interfere with other threads,\n        # file operations or setting st.session_state\n        pass\n    print(f\"Thread done! I slept for {time} seconds.\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSee the [package readme](streamlitextras/threader) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.\n\n\n#### Logger\nImplementation of Loguru set up to work well with this package.\n\n```Python\nimport streamlit as st\nfrom streamlitextras.logger import log\n\ndef main():\n    log.debug(\"My app just started!\")\n    st.write(\"My app\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSee the [package readme](streamlitextras/logger) or [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for more details.\n\n\n#### Other helpers\nSee the [API docs](https://streamlitextras.readthedocs.io/en/latest/api/streamlitextras.html) for a full list of functions and their usage in these files.\n\n###### streamlitextras.webutils\nSome utility functions to run javascript, wrappers around various javascript routines,\nand some other browser related formatting utilities.\n\n```Python\nimport streamlit as st\nfrom streamlitextras.webutils import stxs_javascript, get_user_timezone, \\\n                                    bytes_to_data_uri, trigger_download\n\ndef main():\n    # Returns tz database name can be used with pytz and datetime\n    timezone = get_user_timezone()\n    continent, city = timezone.split(\"/\")\n    stxs_javascript(f\"\"\"alert(\"Hello person from {city}! Welcome to my streamlit app.\");\"\"\"\n\n    uploaded_file = st.file_uploader(\"Upload a file\")\n\n    if uploaded_file:\n        data_uri = bytes_to_data_uri(uploaded_file)\n        # Browser will prompt to save the file\n        trigger_download(data_uri, \"The file you just uploaded.renamed\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nSee the [source code](streamlitextras/webutils.py).\n\n###### streamlitextras.helpers\nClass implementation that streamlines creating basic HTML elements with st.markdown,\nand some other useful functions.\n\nSee the [source code](streamlitextras/helpers.py).\n\n###### streamlitextras.storageservice\nHelper to interact with Google Cloud Storage with a service worker account.\n\nIt has some basic wrapper functions to use the service account to manage buckets and blobs,\nas well as computing hashes from Python bytes objects that match gcloud blobs.\n\nSee the [source code](streamlitextras/storageservice.py) and the [google python api reference](https://googleapis.dev/python/storage/latest/) for more.\n\n```Python\nimport streamlitextras.storageservice as storageservice\n\nwith open(\"my.file\", \"rb\") as f:\n    computed_md5_hash = storageservice.compute_bytes_md5hash(f.read())\n\nbuckets = storageservice.get_buckets() # Returns an iterable\nlist_buckets = []\nfor bucket in buckets:\n    list_buckets.append(buckets)\nbuckets = list_buckets\n\nblobs = get_blobs(buckets[0].name) # Returns an iterable\nlist_blobs = p[]\nfor blob in blobs:\n    list_blobs.append(blob)\nblobs = list_blobs\n\nmy_file_blob = blobs[0] # my.file\n\nassert my_file_blob.md5_hash == computed_md5_hash # True\n```\n\nYou will need to set up a service worker on your google cloud project or firebase project,\nand add the details from its .json key to `.streamlit/secrets.toml`\n\n```TOML\n[gcp_service_account]\ntype = \"\"\nproject_id = \"\"\nprivate_key_id = \"\"\nprivate_key = \"\"\nclient_email = \"\"\nclient_id = \"\"\nauth_uri = \"\"\ntoken_uri = \"\"\nauth_provider_x509_cert_url = \"\"\nclient_x509_cert_url = \"\"\n```\n\n###### streamlitextras.utils\nSome utility functions for Python development.\n\nSee the [source code](streamlitextras/utils.py).\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "Make building with streamlit easier.",
    "version": "0.2.44",
    "project_urls": {
        "Changelog": "https://github.com/blipk/streamlitextras/commits/",
        "Documentation": "https://streamlitextras.readthedocs.io/en/stable/index.html",
        "Download": "https://github.com/blipk/streamlitextras/archive/0.2.44.tar.gz",
        "Homepage": "https://github.com/blipk/streamlitextras"
    },
    "split_keywords": [
        "streamlitextras",
        "streamlit",
        "router",
        "authenticator",
        "javascript",
        "cookie",
        "thread"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4818087bb835f2f1b3a4251e3d1b0ee29616982caec60cede306bda6ecf1259e",
                "md5": "6b96b7c7c09661a9685a7df1a6641dc6",
                "sha256": "5a12c7cd5ecfed15965399a12fef410962c2dc0dd0a9ae05d5dd0ffc82dcb9a7"
            },
            "downloads": -1,
            "filename": "streamlit_base_extras-0.2.44-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6b96b7c7c09661a9685a7df1a6641dc6",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 381465,
            "upload_time": "2023-12-07T14:32:10",
            "upload_time_iso_8601": "2023-12-07T14:32:10.524818Z",
            "url": "https://files.pythonhosted.org/packages/48/18/087bb835f2f1b3a4251e3d1b0ee29616982caec60cede306bda6ecf1259e/streamlit_base_extras-0.2.44-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7482b7494906018ad629807aa89b9bf7eb0b8ab5ceb37ea80f125642ede47bfc",
                "md5": "b851b36675a421b3580af74aaca301db",
                "sha256": "ebb6af67a33b938fa4c7586bc8a1a4526d9b32d8d1337c5620a8d5fcf854f00a"
            },
            "downloads": -1,
            "filename": "streamlit-base-extras-0.2.44.tar.gz",
            "has_sig": false,
            "md5_digest": "b851b36675a421b3580af74aaca301db",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 374385,
            "upload_time": "2023-12-07T14:32:14",
            "upload_time_iso_8601": "2023-12-07T14:32:14.135857Z",
            "url": "https://files.pythonhosted.org/packages/74/82/b7494906018ad629807aa89b9bf7eb0b8ab5ceb37ea80f125642ede47bfc/streamlit-base-extras-0.2.44.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-12-07 14:32:14",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "blipk",
    "github_project": "streamlitextras",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "streamlit",
            "specs": [
                [
                    ">=",
                    "1.23.1"
                ]
            ]
        },
        {
            "name": "urllib3",
            "specs": [
                [
                    "==",
                    "1.26.16"
                ]
            ]
        },
        {
            "name": "requests",
            "specs": []
        },
        {
            "name": "gcloud",
            "specs": []
        },
        {
            "name": "pyjwt",
            "specs": []
        },
        {
            "name": "firebase",
            "specs": []
        },
        {
            "name": "pyrebase4",
            "specs": []
        },
        {
            "name": "sseclient",
            "specs": []
        },
        {
            "name": "PyCryptodome",
            "specs": []
        },
        {
            "name": "requests_toolbelt",
            "specs": []
        },
        {
            "name": "firebase-admin",
            "specs": []
        },
        {
            "name": "google-cloud-storage",
            "specs": []
        },
        {
            "name": "twine",
            "specs": []
        },
        {
            "name": "Sphinx",
            "specs": [
                [
                    "==",
                    "5.2.3"
                ]
            ]
        },
        {
            "name": "sphinx-autobuild",
            "specs": [
                [
                    "==",
                    "2021.3.14"
                ]
            ]
        },
        {
            "name": "sphinx-rtd-theme",
            "specs": [
                [
                    "==",
                    "1.0.0"
                ]
            ]
        },
        {
            "name": "docutils",
            "specs": [
                [
                    "==",
                    "0.16"
                ]
            ]
        },
        {
            "name": "sphinxcontrib-apidoc",
            "specs": []
        }
    ],
    "lcname": "streamlit-base-extras"
}
        
Elapsed time: 0.17353s