Best way to throttle network requests
mikael last edited by
What would be your recommended way of handling the following use case, specifically in Pythonista UI module context:
User is busily typing in a TextView (or a similar UI element). I want the input to be stored on a web service (via HTTP POST).
Saving to the web service is generally fast but subject to all the vagaries of Internet, so I would not like to send an update for every character typed, nor to wait for the response. And since I am sending the whole text typed every time, it does not matter if an occasional update goes awry - but, if the "last" update fails, it needs to be re-sent.
Any suggestions? This seems such a common scenario that I am hoping there's an "established" solution for it.
JonB last edited by
A few things come to mind. In
textview_did_change, you could call
ui.delayto a function which immediately calls
ui.cancel_delays, so that data is only sent when the user stops typing for a bit.
The actual send should probably be in a
ui.in_background, or thread.
you might also keep the connection alive using requests.Session.
ccc last edited by ccc
Another approach would be to use
textview_did_changeas @JonB recommends and then send your data using Python3's asyncio module. Send and forget. You will send more packets to your server than JonB's method but each packet's progress should not block your UI.