Skip to content

Instantly share code, notes, and snippets.

@akbargumbira
Created March 13, 2014 11:25
Show Gist options
  • Save akbargumbira/9526673 to your computer and use it in GitHub Desktop.
Save akbargumbira/9526673 to your computer and use it in GitHub Desktop.
Ugly Fix
def download_url(manager, url, output_path, progress_dialog=None):
"""Download file from url.
:param manager: A QNetworkAccessManager instance
:type manager: QNetworkAccessManager
:param url: URL of file
:type url: str
:param output_path: Output path
:type output_path: str
:param progress_dialog: Progress dialog widget
:returns: True if success, otherwise returns a tuple with format like this
(QNetworkReply.NetworkError, error_message)
:raises: IOError - when cannot create output_path
"""
download_buffer = QByteArray()
# prepare output path
out_file = QFile(output_path)
if not out_file.open(QFile.WriteOnly):
raise IOError(out_file.errorString())
def download_data():
buffer_size = reply.size()
download_buffer.append(reply.read(buffer_size))
# slot to write data to file
def write_data():
"""Write data to a file."""
out_file.write(download_buffer)
out_file.close()
request = QNetworkRequest(QUrl(url))
return_val = QObject.connect(
manager, SIGNAL("finished(QNetworkReply *)"), write_data)
reply = manager.get(request)
reply.readyRead.connect(download_data)
if progress_dialog:
# progress bar
def progress_event(received, total):
"""Update progress.
:param received: Data received so far.
:type received: int
:param total: Total expected data.
:type total: int
"""
# noinspection PyArgumentList
QCoreApplication.processEvents()
progress_dialog.setLabelText("%s / %s" % (received, total))
progress_dialog.setMaximum(total)
progress_dialog.setValue(received)
# cancel
def cancel_action():
"""Cancel download."""
reply.abort()
reply.downloadProgress.connect(progress_event)
progress_dialog.canceled.connect(cancel_action)
# # wait until finished
while not reply.isFinished() and not out_file.size() > 0:
# noinspection PyArgumentList
QCoreApplication.processEvents()
if reply.isFinished() or out_file.size() > 0:
result = reply.error()
if result == QNetworkReply.NoError:
return True, None
else:
return result, str(reply.errorString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment