streamlit / streamlit

Streamlit — A faster way to build and share data apps.
https://streamlit.io
Apache License 2.0
32.51k stars 2.83k forks source link

Native asyncio support #8488

Open thorin-schiffer opened 1 month ago

thorin-schiffer commented 1 month ago

Checklist

Summary

Streamlit needs native asyncio support.

I would like to point the following:

Known problems for now:

So with that said, very ugly workaround that I found working best for now:

@st.cache_resource(show_spinner=False)
def get_event_loop():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    return loop

if not st.session_state.get("event_loop"):
    st.session_state["event_loop"] = get_event_loop()

then pass that event loop wherever your data is coming from, here is motor example:

async def setup_db(force=False):
    if force or not st.session_state.get("db_client"):
        with st.spinner("Loading..."):
            client = AsyncIOMotorClient(
                os.environ["MONGODB_URI"],
                tls=MONGODB_TLS,
                io_loop=st.session_state["event_loop"],
            )
            st.session_state["db_client"] = await init_database(client=client)
            return client

init_database is a call to beanie's init database

I understand that making the entire framework async would require too much work and would prb confuse the ML/AI crowd too much, but streamlit is such a gorgeous framework, the only place it fails in misery is the async

Why?

Asyncio data technologies should be natively or at least easily accessible from streamlit apps.

How?

Runs with asyncio.run() should not result to errors. Concurrent access also should not be broken. Asyncio loop from tornado app should be available in the scripts.

Handling st.* calls async seems quite unimaginable, but at least the functioning asyncio in the eventlets would give us a lot.

Also async support for on_change and on_click callbacks and caching functions.

Additional Context

No response

github-actions[bot] commented 1 month ago

To help Streamlit prioritize this feature, react with a 👍 (thumbs up emoji) to the initial post.

Your vote helps us identify which enhancements matter most to our users.

Visits

vikyw89 commented 1 month ago

2024 and no async support... yet, gonna thumbs this up 10 times

mescanne commented 1 day ago

Hello -

Just a bit of experimentation around Streamlit, threads, and asyncio.

My understanding:

I'm not sure how scalable this is -- threads will be active for each user potentially -- but my approach has been:

I haven't done scaled testing, but this approach seems to be working sensibly in my tests.