def fetchResults(self, search, context, feedback):
        self.dbg_info("start GMF locator search...")
        url = self.service.url
        if not url:
            self.emit_bad_configuration()
            return
        if len(search) < 2:
            return

        params = {
            'query': search,
            'limit': str(self.service.total_limit),
            'partitionlimit': str(self.service.category_limit)
        }
        url = self.url_with_param(url, params)
        self.dbg_info(url.url())

        _request = QNetworkRequest(url)
        _request.setRawHeader(b'User-Agent', self.USER_AGENT)
        request = QgsBlockingNetworkRequest()
        if self.service.authid:
            request.setAuthCfg(self.service.authid)

        response = request.get(_request, False, feedback)
        if response == QgsBlockingNetworkRequest.NoError:
            self.handle_response(request.reply().content())
        else:
            error_msg = request.reply().errorString()
            self.emit_bad_configuration(error_msg)
            self.info(error_msg, Qgis.Critical)
        self.finished.emit()
示例#2
0
def fetch_raw(
    url: str,
    encoding: str = ENCODING,
    authcfg_id: str = "",
    params: Optional[Dict[str, str]] = None,
) -> Tuple[bytes, str]:
    """
    Fetch resource from the internet. Similar to requests.get(url) but is
    recommended way of handling requests in QGIS plugin
    :param url: address of the web resource
    :param encoding: Encoding which will be used to decode the bytes
    :param authcfg_id: authcfg id from QGIS settings, defaults to ''
    :param params: Dictionary to send in the query string
    :return: bytes of the content and default name of the file or empty string
    """
    if params:
        url += "?" + urlencode(params)
    LOGGER.debug(url)
    req = QNetworkRequest(QUrl(url))
    # http://osgeo-org.1560.x6.nabble.com/QGIS-Developer-Do-we-have-a-User-Agent-string-for-QGIS-td5360740.html
    user_agent = QSettings().value("/qgis/networkAndProxy/userAgent",
                                   "Mozilla/5.0")
    user_agent += " " if len(user_agent) else ""
    # noinspection PyUnresolvedReferences
    user_agent += f"QGIS/{Qgis.QGIS_VERSION_INT}"
    user_agent += f" {plugin_name()}"
    # https://www.riverbankcomputing.com/pipermail/pyqt/2016-May/037514.html
    req.setRawHeader(b"User-Agent", bytes(user_agent, encoding))
    request_blocking = QgsBlockingNetworkRequest()
    if authcfg_id:
        request_blocking.setAuthCfg(authcfg_id)
    _ = request_blocking.get(req)
    reply: QgsNetworkReplyContent = request_blocking.reply()
    reply_error = reply.error()
    if reply_error != QNetworkReply.NoError:
        # Error content will be empty in older QGIS versions:
        # https://github.com/qgis/QGIS/issues/42442
        message = (bytes(reply.content()).decode("utf-8") if len(
            bytes(reply.content())) else None)
        # bar_msg will just show a generic Qt error string.
        raise QgsPluginNetworkException(
            message=message,
            error=reply_error,
            bar_msg=bar_msg(reply.errorString()),
        )

    # https://stackoverflow.com/a/39103880/10068922
    default_name = ""
    if reply.hasRawHeader(CONTENT_DISPOSITION_BYTE_HEADER):
        header: QByteArray = reply.rawHeader(CONTENT_DISPOSITION_BYTE_HEADER)
        default_name = bytes(header).decode(encoding).split("filename=")[1]
        if default_name[0] in ['"', "'"]:
            default_name = default_name[1:-1]

    return bytes(reply.content()), default_name