def execute(self): """Download the file at the URL.""" logger.debug("Task {}: preparing to download {}".format(self, self.url)) response = urlopen(self.url) meta = response.info() encoding = response.headers['content-type'].split('charset=')[-1] size = int(meta.getheaders("Content-Length")[0]) logger.debug("Task {}: size={}, encoding={}".format(self, size, encoding)) chunk_size = 4096 if self.filename is None: file = self.file else: file = open(self.filename, "wb") try: keep = True progress = 0.0 percent = 0 self.update(title=t("task.download.title", url=self.url, progress=0), text=t("task.download.downloading", url=self.url, percent=0)) while keep: old_percent = percent progress += chunk_size percent = round((progress / size) * 100, 1) if int(percent) != int(old_percent): self.update(title=t("task.download.title", url=self.url, percent=int(percent)), text=t("task.download.downloading", url=self.url, percent=int(percent)), progress=int(percent)) chunk = response.read(chunk_size) if not chunk: keep = False file.write(chunk) file.seek(0) finally: if self.filename is not None: file.close()
def run(self): """Run in a separate thread. This method will call 'execute' in a separate thread and will catch specific exceptions. It shouldn't be necessary to override this method. """ try: self.execute() except InterruptTask: self.cancel() except Exception: logger.exception("Exception in task {}:".format(self)) else: logger.debug("Completed the task {} successfully".format(self)) finally: if self.dialog: self.dialog.Destroy()
def cancel(self): """Should a specific action be performed when cancelled?""" logger.debug("Cancelled the task {}".format(self))
def start(self): """Start the thread and display the dialog.""" logger.debug("Starting the task {}".format(self)) Thread.start(self) if self.dialog: self.dialog.ShowModal()