From: Michael Tremer Date: Wed, 30 Nov 2016 16:38:52 +0000 (+0100) Subject: ui.progressbar: Support python context X-Git-Tag: 0.9.28~1285^2~1457 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6ee6bae9bec9fe62a6bd1b6d88d9f544880cf61a;p=pakfire.git ui.progressbar: Support python context This patch allows us to use the progressbar inside a with statement which makes code shorter and sweeter and we need to take care less about the progressbar implementation where ever we are using it. e.g.: p = ProgressBar() ... with p: do something p.update(i) Signed-off-by: Michael Tremer --- diff --git a/src/pakfire/http.py b/src/pakfire/http.py index 2fc1195c1..a619900cd 100644 --- a/src/pakfire/http.py +++ b/src/pakfire/http.py @@ -182,7 +182,7 @@ class Client(object): raise MaxTriesExceededError - def retrieve(self, url, filename, show_progress=True, message=None, **kwargs): + def retrieve(self, url, filename, message=None, **kwargs): p = None if message is None: @@ -190,31 +190,24 @@ class Client(object): buffer_size = 100 * 1024 # 100k - # Make a progressbar - if show_progress: - p = self._make_progressbar(message) - # Prepare HTTP request r = self._make_request(url, **kwargs) # Send the request - with self._send_request(r) as f: - # Try setting progress bar to correct maximum value - # XXX this might need a function in ProgressBar - l = self._get_content_length(f) - if p: + with self._make_progressbar(message) as p: + with self._send_request(r) as f: + # Try setting progress bar to correct maximum value + # XXX this might need a function in ProgressBar + l = self._get_content_length(f) p.value_max = l - buf = f.read(buffer_size) - while buf: - l = len(buf) - if p: - p.update_increment(l) + while True: + buf = f.read(buffer_size) + if not buf: + break - buf = f.read(buffer_size) - - if p: - p.finish() + l = len(buf) + p.update_increment(l) def _get_content_length(self, response): s = response.getheader("Content-Length") @@ -244,8 +237,8 @@ class Client(object): return "Basic %s" % authstring.decode("ascii") - def _make_progressbar(self, message=None): - p = progressbar.ProgressBar() + def _make_progressbar(self, message=None, **kwargs): + p = progressbar.ProgressBar(**kwargs) # Show message (e.g. filename) if message: @@ -277,7 +270,7 @@ class Client(object): w = progressbar.WidgetETA() p.add(w) - return p.start() + return p class HTTPError(errors.Error): diff --git a/src/pakfire/ui/progressbar.py b/src/pakfire/ui/progressbar.py index afba9adbc..ecb241524 100644 --- a/src/pakfire/ui/progressbar.py +++ b/src/pakfire/ui/progressbar.py @@ -178,6 +178,17 @@ class ProgressBar(object): return 0 + # Implement using progressbar as context + + def __enter__(self): + # Start the progressbar + self.start() + + return self + + def __exit__(self, type, value, traceback): + self.finish() + def format_updatable(widget, pbar): if hasattr(widget, "update"):