I wanted to now share my conclusions so that others can benefit from them too. To do this I am going to first explain how this works, and secondly I have created a Python Snippet and added it to the Python Snippets libray so there is a great working example you folks can play with. You can use Acire to load the snippet and play with it. This is the first
gio snippet, and I hope there will be many more.
The goal I set out with was to download a file without freezing the GUI. This was somewhat inspired from a recent Shot Of Jaq shot that we did on async programming, and I used this app as a good example to play with. Typically I had downloaded files the manual way and this had blocked my GUI hard, but I was aware that this is exactly what
gio, part of the GNOME platform is here to solve.
The way async basically works is that you kick off an operation and then you wait for confirmation of the result before you proceed. It is the opposite of procedural programming: you don’t kick off an operation and in the next line process it. When you do things the async way, you start an operation and then tell it what callback should be called when it is complete. It feels very event-driven: kind of how you connect a handler to a signal in a widget so that when that signal is generated, the handler is called.
When I started playing with this the docs insinuated that
read_finish() were what I needed to use. I started off with code that looked a little like this:
def download_latest_shot(self): audiourl = "http://....the url to the Ogg file...." self.shot_stream = gio.File(audiourl) self.shot_stream.read_async(self.download_latest_shot_complete)
It then calls this callback:
def download_latest_shot_complete(self, gdaemonfile, result): f = self.shot_stream.read_finish(result).read() outputfile = open("/home/jono/Desktop/shot.ogg","w") outputfile.writelines(f)
After some helpful notes from the GNOME community, it turned out that what I really needed to use was
load_contents_async() to download the full content of the file (
read_async() merely kicks off a read operation) and
load_contents_finish() as the callback that is called when it is complete. This worked great for me.
As such, here is the snippet which I have added to the Python Snippets library which downloads the Ubuntu HTML index page, shows it in a GUI without blocking it and writes it to the disk:
I am still pretty new to this, and I am sure there is plenty that can be improved in the snippet, so feel free submit a merge request if you would like to improve it. Hope this helps!