Blocking function awaiting response from widget #678
-
Running in a notebook pyhton kernel, is there a pattern for a blocking wait on a response from the widget js? import threading
from anywidget import AnyWidget
from traitlets import Unicode, observe
from IPython.display import display
class BlockingMessageWidget(AnyWidget):
message = Unicode('').tag(sync=True)
reply = Unicode('').tag(sync=True)
def __init__(self):
super().__init__()
def sendMessage(self, msg):
self.reply = ''
self.message = msg
def blocking_reply(self, timeout=None):
# something
return self.reply
async def await_blocking_reply(self, timeout=None):
# something
return self.reply
_esm = """
export function render({ model, el }) {
const processMessage = (msg) => {
// Simulate some processing
return new Promise(resolve => {
setTimeout(() => {
resolve(`Processed: ${msg}`);
}, 2000);
});
};
model.on('change:message', async () => {
const msg = model.get('message');
if (msg) {
const reply = await processMessage(msg);
model.set('reply', reply);
model.save_changes();
}
});
el.textContent = 'Blocking Message Widget';
}
""" and then:
And either:
or:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I was surprised by how tricky this is. There are libraries like Some relevant discussion and links can be found in this ipywidgets issue: jupyter-widgets/ipywidgets#3039 |
Beta Was this translation helpful? Give feedback.
-
I note that there is now JavaScript Promise Integration in Pyodide, with a from pyodide.ffi import run_sync
from js import fetch
async def async_http_request(url):
resp = await fetch(url)
return await resp.text()
def make_http_request(url):
# make_http_request is a synchronous function that will block until
# async_http_request() completes
return run_sync(async_http_request(url))
# Use make_http_request in a non-async function 🎉
def do_something_with_request(url):
result = make_http_request(url)
do_something_with(result) So.. does that help? |
Beta Was this translation helpful? Give feedback.
Ah, thanks for that.
The
jupyter_ui_poll
approach appears to work in a jupyter served browser environment: