Skip to content

Instantly share code, notes, and snippets.

@attentive
Last active September 26, 2020 23:10
Show Gist options
  • Save attentive/fd689d07b0046a5b2f43e7e3fc5db38d to your computer and use it in GitHub Desktop.
Save attentive/fd689d07b0046a5b2f43e7e3fc5db38d to your computer and use it in GitHub Desktop.
Use QgsBlockingNetworkRequest to download a file
# Just chucking this here because the documentation's a little weak and someone
# might find it useful. This has changed a few times in QGIS history.
# NB this was hacked up from some code that worked in QGIS 3.4, 3.10 and 3.14, it
# may have minor indentation issues but … this is the gist of it.
from qgis.PyQt.QtCore import QObject, QUrl
from qgis.PyQt.QtNetwork import QNetworkReply, QNetworkRequest
from qgis.core import Qgis, QgsMessageLog, QgsBlockingNetworkRequest
from .utils import guiError, qgsDebug
def doSomething(content):
"""Do something with the content of the downloaded file."""
textContent = bytes(content).decode()
pass
def downloadFile(self, url):
"""Download a file with QgsBlockingNetworkRequest."""
request = QNetworkRequest(url))
# use a blocking request here
blockingRequest = QgsBlockingNetworkRequest()
result = blockingRequest.get(request)
if result == QgsBlockingNetworkRequest.NoError:
reply = blockingRequest.reply()
if reply.error() == QNetworkReply.NoError:
doSomething(reply.content())
else:
QgsMessageLog.logMessage(reply.errorString(), tag="Gist Error", level=Qgis.Info)
else:
QgsMessageLog.logMessage(reply.errorString(), tag="Gist Error", level=Qgis.Info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment