Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
async web request from a Scene script
-
I’d like to periodically issue an HTTP request to a URL which will return a result via JSON. This is in a scene based script. So I’d like to do it async so the scene updating doesn’t stop while the request is waiting.
I’m new to async in python. I found asyncio and I see pythonista includes that. Many examples also use aiohttp which does not appear to be included in pythonista.
Can anyone point me to a simple example of using asyncio only to do this which will work in a scene based script?
-
Install stash: https://github.com/ywangd/stash
That will let you use pip to install aiohttp and aiohttp-requests.In general, you can install most pure python packages (no compiled code) that don't rely on
subprocess
. -
@JonB For my own info, is that very different of using the json request in another Thread than the scene?
-
@cvp I'm not an expert in async. Google tells me this
https://realpython.com/python-concurrency/#how-to-speed-up-an-io-bound-programAsyncio/aiohttp is I believe the fastest way to do io heavy work. I think they would be similar, but there are some penalties for whatever context shifting has to happen when using threads. Asyncio is built into the language, and is basically handling everything in one thread.
I suspect if you are only a talking to one page, performance would be the same. Asyncio shines when doing lots of io.
For scene work, I suspect either would work -- I would tend to use threading, because I never fully wrapped my brain around the async /wait mechanisms in python, and it feels very unnatural to me.
-
By the way
https://forum.omz-software.com/topic/4456/ui-and-aiohttp
Has an example in pythonista with a UI.View and update -- this would look similar in Scene, I think.For just grabbing one webpage, I suspect ui.in_background could also work, though it will block other in_background calls.(and the main console) until the function returns
-
@JonB thanks a lot for all your (as usual, skilled) explanations. I remember my (very far) past experience with multitasking.
-
Thanks for the replies! Will dig into these and see what I can get working.