stlite icon indicating copy to clipboard operation
stlite copied to clipboard

Running Async code

Open aghasemi opened this issue 3 years ago • 2 comments

Hi,

Is there a way to run async code (e.g. pyodide.http) in stlite? I tried asyncio.get_event_loop and it did work (nothing was executed). Is there a working example of it?

aghasemi avatar Aug 26 '22 20:08 aghasemi

I tried asyncio.get_event_loop and it did work (nothing was executed)

I can't get the point. asyncio.get_event_loop just returns the current event loop which is on the stlite env an instance of WebLoop, and does not execute anything.

whitphx avatar Aug 28 '22 15:08 whitphx

Apart that, there is a blocking API to access remote resources, pyodide.http.open_url

import pyodide
import streamlit as st

url = "https://raw.githubusercontent.com/fivethirtyeight/data/master/airline-safety/airline-safety.csv"  # Sample from streamlit-aggrid https://github.com/PablocFonseca/streamlit-aggrid
res = pyodide.http.open_url(url)
text = res.getvalue()

st.write(text)

Async, non-blocking API, pyodide.http.pyfetch is also there, but it is not good to use with stlite or Streamlit (#125 ) because Streamlit does not support the top-level await so the response cannot be passed to st.* such as st.write() in a normal way.

import pyodide
import streamlit as st
import asyncio

loop = asyncio.get_event_loop()

async def access_remote_test():
        url = "https://raw.githubusercontent.com/fivethirtyeight/data/master/airline-safety/airline-safety.csv"  # Sample from streamlit-aggrid https://github.com/PablocFonseca/streamlit-aggrid
        res = await pyodide.http.pyfetch(url)
        data = await res.bytes()
        text = data.decode("utf8")
        print(text)

loop.create_task(access_remote_test())

whitphx avatar Aug 28 '22 16:08 whitphx

I'm not sure I understood you, sorry. Do you mean there is no way to run an async function in (normal) Streamlit, e.g. by waiting for the result or something? Sorry I have very limited experience in Python async/await

aghasemi avatar Sep 02 '22 22:09 aghasemi

Do you mean there is no way to run an async function in (normal) Streamlit,

Yes.

Precisely, just running async function is possible as the second code block above, but using its result in a normal Streamlit script is difficult (maybe impossible).

whitphx avatar Sep 09 '22 14:09 whitphx