def _onNetworkFinished(self, reply: QNetworkReply): status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) url_string = reply.url().toString() if "modifier" in url_string: if status_code == 404: print("server was not found!") self._failed_update_modifier_timer.start() return data = bytes(reply.readAll()) try: self._modifiers = json.loads(data) except: print("Failed to get modifier data") self._failed_update_modifier_timer.start() return self.modifiersChanged.emit() elif "RFID" in url_string: if status_code != 404: self._serial_worker.setReadResult(True) self.setAuthenticationRequired(False) else: self._serial_worker.setReadResult(False) self.setAuthenticationRequired(True) else: # Yeah it's hackish, but it's faster than building a real system. For now we don't need more if status_code == 404: print("Server was not found!") self._failed_update_nodes_timer.start() return data = bytes(reply.readAll()) try: data = json.loads(data) for item in data: new_node = Node(item["node_id"]) new_node.updateServerUrl( self._zeroconf_worker.server_address) self._data.append(new_node) new_node.serverReachableChanged.connect( self.serverReachableChanged) self._data = sorted(self._data, key=lambda node: node.id) # sort by age self._data.reverse() self.nodesChanged.emit() except: print("Failed to get modifier data") self._failed_update_nodes_timer.start() return
def gotResponse(self, QNetworkReply): try: status = QNetworkReply.attribute( QNetworkRequest.HttpStatusCodeAttribute) except Exception as e: log('[e] http/yaml error: %s' % str(e)) self.updatesLabel.setText('Error') return if status != 200: self.updatesLabel.setText('Network error: ' + str(status)) return try: response = QNetworkReply.readAll() response = str(response, 'utf-8') ver = safe_load(response) except Exception as e: log('[e] http/yaml error: %s' % str(e)) self.updatesLabel.setText('error') return if ver is None: self.updatesLabel.setText('<network error>') return if 'version' in ver and 'date' in ver: verStr = 'Last published version is %s, build %s.' % ( ver['version'], ver['date']) self.updatesLabel.setText(verStr)
def _finishedCallback(self, reply: QNetworkReply) -> None: Logger.log("i", "Finished callback %s %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), reply.url().toString()) status_code = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) # type: int # check if we should retry the last chunk if self._retries < self.MAX_RETRIES and status_code in self.RETRY_HTTP_CODES: self._retries += 1 Logger.log("i", "Retrying %s/%s request %s", self._retries, self.MAX_RETRIES, reply.url().toString()) try: self._uploadChunk() except ValueError: # Asynchronously it could have completed in the meanwhile. pass return # Http codes that are not to be retried are assumed to be errors. if status_code > 308: self._errorCallback(reply, None) return Logger.log( "d", "status_code: %s, Headers: %s, body: %s", status_code, [bytes(header).decode() for header in reply.rawHeaderList()], bytes(reply.readAll()).decode()) self._chunkUploaded()
def on_response(self, reply: QNetworkReply): self.progress_bar.set_part(10, 1, 'Чтение ответа') error_code = reply.error() if error_code == QNetworkReply.NoError: bytes_string = reply.readAll() json_ar = json.loads(str(bytes_string, 'utf-8')) print(json_ar) if json_ar['status'] == 'OK': self.progress_bar.increment() self.read_response.emit(json_ar['data'], self.progress_bar) self.finish.emit(json_ar['data']) self.progress_bar.on_finish('Успешно синхронизированно') else: self.progress_bar.abord() self.button.setEnabled(True) self.error.emit(str(error_code)) self.progress_bar.on_finish( f'Завершено с ошибкой {json_ar["message"]}') else: print(error_code) self.progress_bar.abord() self.button.setEnabled(True) self.error.emit(error_code) self.progress_bar.on_finish(f'Завершено с ошибкой {error_code}')
def _load_icon_and_cache(self, http_response: QNetworkReply): icon_url = http_response.request().url().toString() icon_data = self.icon_cache.get(icon_url) icon_was_cached = True if not icon_data: icon_bytes = http_response.readAll() if not icon_bytes: return icon_was_cached = False pixmap = QPixmap() pixmap.loadFromData(icon_bytes) if not pixmap.isNull(): icon = QIcon(pixmap) icon_data = {'icon': icon, 'bytes': icon_bytes} self.icon_cache.add(icon_url, icon_data) if icon_data: for idx, app in enumerate(self.window.pkgs): if app.model.icon_url == icon_url: col_name = self.item(idx, 0) col_name.setIcon(icon_data['icon']) if app.model.supports_disk_cache( ) and app.model.get_disk_icon_path(): if not icon_was_cached or not os.path.exists( app.model.get_disk_icon_path()): self.window.manager.cache_to_disk( pkg=app.model, icon_bytes=icon_data['bytes'], only_icon=True)
def loadJsonFromReply(reply: QNetworkReply) -> Optional[List[Dict[str, Any]]]: try: result = json.loads(bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.logException("w", "Unable to decode JSON from reply.") return None return result
def _parseReply(cls, reply: QNetworkReply) -> Dict[str, ClusterMaterial]: try: remote_materials = json.loads( reply.readAll().data().decode("utf-8")) return { material["guid"]: ClusterMaterial(**material) for material in remote_materials } except UnicodeDecodeError: Logger.log( "e", "Request material storage on printer: I didn't understand the printer's answer." ) except json.JSONDecodeError: Logger.log( "e", "Request material storage on printer: I didn't understand the printer's answer." ) except ValueError: Logger.log( "e", "Request material storage on printer: Printer's answer had an incorrect value." ) except TypeError: Logger.log( "e", "Request material storage on printer: Printer's answer was missing a required value." )
def parseReplyAsBytes(cls, reply: QNetworkReply) -> Tuple[int, bytes]: """ Parse the given API reply into a status code and bytes. :param reply: The reply from the server. :return: A tuple with a status code and the response body as bytes. """ status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) return status_code, reply.readAll().data()
def _errorCallback(self, reply: QNetworkReply, error: QNetworkReply.NetworkError) -> None: """Handles an error uploading.""" body = bytes(reply.readAll()).decode() Logger.log("e", "Received error while uploading: %s", body) self.stop() self._on_error()
def _onGetProjectFailed(self, reply: QNetworkReply, error: QNetworkReply.NetworkError) -> None: reply_string = bytes(reply.readAll()).decode() self.setHasPreselectedProject(False) Logger.log( "w", "Something went wrong while trying to retrieve a the preselected Digital Library project. Error: {}" .format(reply_string))
def _parseReply(reply: QNetworkReply) -> Tuple[int, Dict[str, Any]]: status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) try: response = bytes(reply.readAll()).decode() return status_code, json.loads(response) except (UnicodeDecodeError, JSONDecodeError, ValueError) as err: Logger.logException("e", "Could not parse the cluster response: %s", err) return status_code, {"errors": [err]}
def sendingFinished(self, reply: QNetworkReply): if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200: Logger.log( "e", "Received error code from printer when syncing material: {code}" .format(code=reply.attribute( QNetworkRequest.HttpStatusCodeAttribute))) Logger.log("e", reply.readAll().data().decode("utf-8"))
def _onRequestFinished(self, reply: QNetworkReply) -> None: if reply.error() == QNetworkReply.TimeoutError: Logger.log("w", "Got a timeout.") self.setViewPage("errored") self.resetDownload() return if reply.error() == QNetworkReply.HostNotFoundError: Logger.log("w", "Unable to reach server.") self.setViewPage("errored") self.resetDownload() return if reply.operation() == QNetworkAccessManager.GetOperation: for response_type, url in self._request_urls.items(): if reply.url() == url: if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200: try: json_data = json.loads(bytes(reply.readAll()).decode("utf-8")) # Check for errors: if "errors" in json_data: for error in json_data["errors"]: Logger.log("e", "%s", error["title"]) return # Create model and apply metadata: if not self._models[response_type]: Logger.log("e", "Could not find the %s model.", response_type) break self._server_response_data[response_type] = json_data["data"] self._models[response_type].setMetadata(self._server_response_data[response_type]) if response_type is "packages": self._models[response_type].setFilter({"type": "plugin"}) self.reBuildMaterialsModels() self.reBuildPluginsModels() self._notifyPackageManager() elif response_type is "authors": self._models[response_type].setFilter({"package_types": "material"}) self._models[response_type].setFilter({"tags": "generic"}) self.metadataChanged.emit() if self.isLoadingComplete(): self.setViewPage("overview") except json.decoder.JSONDecodeError: Logger.log("w", "Received invalid JSON for %s.", response_type) break else: Logger.log("w", "Unable to connect with the server, we got a response code %s while trying to connect to %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), reply.url()) self.setViewPage("errored") self.resetDownload() elif reply.operation() == QNetworkAccessManager.PutOperation: # Ignore any operation that is not a get operation pass
def _onRequestFinished(self, reply: QNetworkReply) -> None: if reply.error() == QNetworkReply.TimeoutError: Logger.log("w", "Got a timeout.") self.setViewPage("errored") self.resetDownload() return if reply.error() == QNetworkReply.HostNotFoundError: Logger.log("w", "Unable to reach server.") self.setViewPage("errored") self.resetDownload() return if reply.operation() == QNetworkAccessManager.GetOperation: for response_type, url in self._request_urls.items(): if reply.url() == url: if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200: try: json_data = json.loads(bytes(reply.readAll()).decode("utf-8")) # Check for errors: if "errors" in json_data: for error in json_data["errors"]: Logger.log("e", "%s", error["title"]) return # Create model and apply metadata: if not self._models[response_type]: Logger.log("e", "Could not find the %s model.", response_type) break self._server_response_data[response_type] = json_data["data"] self._models[response_type].setMetadata(self._server_response_data[response_type]) if response_type is "packages": self._models[response_type].setFilter({"type": "plugin"}) self.reBuildMaterialsModels() self.reBuildPluginsModels() elif response_type is "authors": self._models[response_type].setFilter({"package_types": "material"}) self._models[response_type].setFilter({"tags": "generic"}) self.metadataChanged.emit() if self.isLoadingComplete(): self.setViewPage("overview") except json.decoder.JSONDecodeError: Logger.log("w", "Received invalid JSON for %s.", response_type) break else: Logger.log("w", "Unable to connect with the server, we got a response code %s while trying to connect to %s", reply.attribute(QNetworkRequest.HttpStatusCodeAttribute), reply.url()) self.setViewPage("errored") self.resetDownload() elif reply.operation() == QNetworkAccessManager.PutOperation: # Ignore any operation that is not a get operation pass
def _parseReply(reply: QNetworkReply) -> Tuple[int, Dict[str, Any]]: status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) try: response = bytes(reply.readAll()).decode() return status_code, json.loads(response) except (UnicodeDecodeError, JSONDecodeError, ValueError) as err: error = CloudError(code=type(err).__name__, title=str(err), http_code=str(status_code), id=str(time()), http_status="500") Logger.logException("e", "Could not parse the stardust response: %s", error.toDict()) return status_code, {"errors": [error.toDict()]}
def _onGetPreviewImageFinished(self, reply: QNetworkReply) -> None: reply_url = reply.url().toString() uuid = reply_url[reply_url.find("print_jobs/")+len("print_jobs/"):reply_url.rfind("/preview_image")] print_job = findByKey(self._print_jobs, uuid) if print_job: image = QImage() image.loadFromData(reply.readAll()) print_job.updatePreviewImage(image)
def _sendingFinished(self, reply: QNetworkReply) -> None: if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) != 200: Logger.log("w", "Error while syncing material: %s", reply.errorString()) return body = reply.readAll().data().decode('utf8') if "not added" in body: # For some reason the cluster returns a 200 sometimes even when syncing failed. return # Inform the user that materials have been synced. This message only shows itself when not already visible. # Because of the guards above it is not shown when syncing failed (which is not always an actual problem). MaterialSyncMessage(self.device).show()
def _parse_result(self, reply: QNetworkReply) -> str: if reply.error(): print(reply.errorString()) print('parsing reply') text = 'no help available' try: text = bytes(reply.readAll()).decode('ascii', 'ignore') except Exception as e: print(e) pass return text
def _from_reply(self, reply: QtNetwork.QNetworkReply): """Updates the Response object with the remaining data from the reply.""" # Read the reply's body if reply.isReadable(): self.raw_content.seek(0) self.raw_content.write(reply.readAll()) # Store the cookies manager: QtNetwork.QNetworkAccessManager = reply.manager() jar: QtNetwork.QNetworkCookieJar = manager.cookieJar() object.__setattr__(self, 'cookies', {c.name().data().decode(): c.value() for c in jar.allCookies()})
def base_handler(self, reply: QNetworkReply): try: response = json.loads(str(reply.readAll(), encoding='utf-8')) status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) except: self.parent.warn.add_warn("Http解析错误") return if reply.error() != QNetworkReply.NoError: self.handler_error(response, status_code) else: self.data.emit(response)
def getResult(self, reply: QNetworkReply): error = reply.error() # request was successfully made if error == QNetworkReply.NoError: data = reply.readAll() self.successCallback(str(data, 'utf-8')) else: # request was failed errorStr = reply.errorString() self.errorCallback(errorStr)
def _createNewLibraryProjectFailed(self, reply: QNetworkReply, error: QNetworkReply.NetworkError) -> None: reply_string = bytes(reply.readAll()).decode() self._project_creation_error_text = "Something went wrong while creating the new project. Please try again." if reply_string: reply_dict = json.loads(reply_string) if "errors" in reply_dict and len(reply_dict["errors"]) >= 1 and "title" in reply_dict["errors"][0]: self._project_creation_error_text = "Error while creating the new project: {}".format(reply_dict["errors"][0]["title"]) self.projectCreationErrorTextChanged.emit() self.setCreatingNewProjectStatus(RetrievalStatus.Failed) Logger.log("e", "Something went wrong while trying to create a new a project. Error: {}".format(reply_string))
def _parseReply(cls, reply: QNetworkReply) -> Dict[str, ClusterMaterial]: try: remote_materials = json.loads(reply.readAll().data().decode("utf-8")) return {material["guid"]: ClusterMaterial(**material) for material in remote_materials} except UnicodeDecodeError: Logger.log("e", "Request material storage on printer: I didn't understand the printer's answer.") except json.JSONDecodeError: Logger.log("e", "Request material storage on printer: I didn't understand the printer's answer.") except ValueError: Logger.log("e", "Request material storage on printer: Printer's answer had an incorrect value.") except TypeError: Logger.log("e", "Request material storage on printer: Printer's answer was missing a required value.")
def handleNetworkData(self, networkReply: QNetworkReply): if networkReply.error() == QNetworkReply.NoError: choices = [] response = networkReply.readAll() xml = QXmlStreamReader(response) while not xml.atEnd(): xml.readNext() if xml.tokenType() == QXmlStreamReader.StartElement: if xml.name() == 'suggestion': string = xml.attributes().value('data') choices.append(string) self.showCompletion(choices) networkReply.deleteLater()
def done(self, reply: QNetworkReply): if reply.error() != QNetworkReply.NoError: sys.stderr.write(reply.errorString()) return try: json_data = json.loads(str(reply.readAll(), 'utf-8')) reply.deleteLater() latest = json_data.get('tag_name') current = qApp.applicationVersion() self.parent.update_available(latest, current) except json.JSONDecodeError: self.logger.exception('Error retrieving data', exc_info=True) raise
def done(self, reply: QNetworkReply) -> None: if reply.error() != QNetworkReply.NoError: self.logger.error(reply.errorString()) sys.stderr.write(reply.errorString()) return if os.getenv('DEBUG', False): self.log_request(reply) # noinspection PyTypeChecker jsonobj = json.loads(str(reply.readAll(), 'utf-8')) reply.deleteLater() latest = parse_version(jsonobj.get('tag_name')) current = parse_version(qApp.applicationVersion()) self.mbox.show_result(latest, current)
def _parseReply(reply: QNetworkReply) -> Tuple[int, Optional[Union[List[Any], Dict[str, Any]]]]: """ Parse the given JSON network reply into a status code and JSON object. :param reply: The reply from the server. :return: A tuple with a status code and a dictionary. """ status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) try: response = bytes(reply.readAll()).decode() return status_code, json.loads(response) except (UnicodeDecodeError, JSONDecodeError, ValueError) as err: Logger.logException("e", "Could not parse the API response: %s", err) return status_code, None
def parseReplyAsJson(cls, reply: QNetworkReply ) -> Tuple[int, Optional[Union[Dict[str, Any], List[Dict[str, Any]]]]]: """ Parse the given API reply into a status code and JSON object. :param reply: The reply from the server. :return: A tuple with a status code and the response body as JsonObject. """ status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) try: response = reply.readAll().data().decode() return status_code, json.loads(response) except (UnicodeDecodeError, JSONDecodeError, ValueError) as err: Logger.log("e", "Could not parse the API response: %s", err) return status_code, None
def _parseReply(reply: QNetworkReply) -> Tuple[int, Dict[str, Any]]: """Parses the given JSON network reply into a status code and a dictionary, handling unexpected errors as well. :param reply: The reply from the server. :return: A tuple with a status code and a dictionary. """ status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) try: response = bytes(reply.readAll()).decode() return status_code, json.loads(response) except (UnicodeDecodeError, JSONDecodeError, ValueError) as err: Logger.logException("e", "Could not parse the cluster response: %s", err) return status_code, {"errors": [err]}
def on_finish(self, reply: QNetworkReply): if reply.error() == QNetworkReply.NoError: bytes_string = reply.readAll() data = JsonParser.read(str(bytes_string, 'utf-8')) response = Response.load(**data, class_=self.response_type) if response.status == response.Status.OK: self.response.emit(response.data) else: self.error.emit(response) else: QMessageBox().information( None, "Загрузка информации с сервера", f"Сервер не смог ответить на запрос.\n код ошибки: {str(reply.error())}" ) self.deleteLater()
def done(self, reply: QNetworkReply) -> None: if reply.error() != QNetworkReply.NoError: self.logger.error(reply.errorString()) sys.stderr.write(reply.errorString()) return if os.getenv('DEBUG', False): self.log_request(reply) try: jsonobj = loads(str(reply.readAll(), 'utf-8')) reply.deleteLater() latest = jsonobj.get('tag_name') current = qApp.applicationVersion() self.mbox.show_result(latest, current) except JSONDecodeError: self.logger.exception('Updater JSON decoding error', exc_info=True) raise
def saveServerFinished(self, reply: QNetworkReply): # if error on server occured if reply.error(): QMessageBox.critical(self.app, 'Query error', reply.errorString()) return try: data = loads(bytes(reply.readAll())) QMessageBox.information(self.app, 'Success query', data['message']) except Exception as e: QMessageBox.critical(self.app, 'Query error', 'Error in parsing') print(e) return # save path to clipboard cb: QClipboard = QApplication.clipboard() cb.setText(data['path'], mode=cb.Clipboard)
def login_response(self, response: QNetworkReply): self.is_waiting = False self.login_button.setEnabled(True) err = response.error() if err == QNetworkReply.NoError: reply = str(response.readAll(), 'utf-8') reply_json = json.loads(reply) print(reply_json) if "success" in reply_json and reply_json["success"]: self.state.login(reply_json["email"], reply_json["score"]) self.state.sensor_values = eval(reply_json["sensor_data"]) self.loginSuccess.emit() self.close() else: self.error_dialog.showMessage('아이디나 비밀번호가 맞지 않습니다!') else: self.error_dialog.showMessage("서버 연결에 실패했습니다. 에러 코드=" + str(err))
def _onRequestFinished(self, reply: QNetworkReply) -> None: http_status_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) if not http_status_code: # Received no or empty reply return if reply.operation() == QNetworkAccessManager.PostOperation: if "/plugin/appkeys/request" in reply.url().toString(): # Initial AppKey request if http_status_code == 201 or http_status_code == 202: Logger.log("w", "Start polling for AppKeys decision") if not self._appkey_request: return self._appkey_request.setUrl(reply.header(QNetworkRequest.LocationHeader)) self._appkey_request.setRawHeader(b"Content-Type", b"") self._appkey_poll_timer.start() elif http_status_code == 404: Logger.log("w", "This instance of OctoPrint does not support AppKeys") self._appkey_request = None # type: Optional[QNetworkRequest] else: response = bytes(reply.readAll()).decode() Logger.log("w", "Unknown response when requesting an AppKey: %d. OctoPrint said %s" % (http_status_code, response)) self._appkey_request = None # type: Optional[QNetworkRequest] if reply.operation() == QNetworkAccessManager.GetOperation: if "/plugin/appkeys/probe" in reply.url().toString(): # Probe for AppKey support if http_status_code == 204: self._appkeys_supported = True else: self._appkeys_supported = False self.appKeysSupportedChanged.emit() if "/plugin/appkeys/request" in reply.url().toString(): # Periodic AppKey request poll if http_status_code == 202: self._appkey_poll_timer.start() elif http_status_code == 200: Logger.log("d", "AppKey granted") self._appkey_request = None # type: Optional[QNetworkRequest] try: json_data = json.loads(bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.log("w", "Received invalid JSON from octoprint instance.") return self._keys_cache[self._appkey_instance_id] = json_data["api_key"] self.appKeyReceived.emit() elif http_status_code == 404: Logger.log("d", "AppKey denied") self._appkey_request = None # type: Optional[QNetworkRequest] else: response = bytes(reply.readAll()).decode() Logger.log("w", "Unknown response when waiting for an AppKey: %d. OctoPrint said %s" % (http_status_code, response)) self._appkey_request = None # type: Optional[QNetworkRequest] if "api/settings" in reply.url().toString(): # OctoPrint settings dump from /settings: self._instance_in_error = False if http_status_code == 200: Logger.log("d", "API key accepted by OctoPrint.") self._instance_api_key_accepted = True try: json_data = json.loads(bytes(reply.readAll()).decode("utf-8")) except json.decoder.JSONDecodeError: Logger.log("w", "Received invalid JSON from octoprint instance.") json_data = {} if "feature" in json_data and "sdSupport" in json_data["feature"]: self._instance_supports_sd = json_data["feature"]["sdSupport"] if "webcam" in json_data and "streamUrl" in json_data["webcam"]: stream_url = json_data["webcam"]["streamUrl"] if stream_url: #not empty string or None self._instance_supports_camera = True elif http_status_code == 401: Logger.log("d", "Invalid API key for OctoPrint.") self._instance_api_key_accepted = False elif http_status_code == 502 or http_status_code == 503: Logger.log("d", "OctoPrint is not running.") self._instance_api_key_accepted = False self._instance_in_error = True self._instance_responded = True self.selectedInstanceSettingsChanged.emit()
def _onRequestFinished(self, reply: QNetworkReply) -> None: if reply.error() == QNetworkReply.TimeoutError: Logger.log("w", "Got a timeout.") self.setViewPage("errored") self.resetDownload() return if reply.error() == QNetworkReply.HostNotFoundError: Logger.log("w", "Unable to reach server.") self.setViewPage("errored") self.resetDownload() return if reply.operation() == QNetworkAccessManager.GetOperation: for type, url in self._request_urls.items(): if reply.url() == url: try: json_data = json.loads(bytes(reply.readAll()).decode("utf-8")) # Check for errors: if "errors" in json_data: for error in json_data["errors"]: Logger.log("e", "%s", error["title"]) return # Create model and apply metadata: if not self._models[type]: Logger.log("e", "Could not find the %s model.", type) break # HACK: Eventually get rid of the code from here... if type is "plugins_showcase" or type is "materials_showcase": self._metadata["plugins_showcase"] = json_data["data"]["plugin"]["packages"] self._models["plugins_showcase"].setMetadata(self._metadata["plugins_showcase"]) self._metadata["materials_showcase"] = json_data["data"]["material"]["authors"] self._models["materials_showcase"].setMetadata(self._metadata["materials_showcase"]) else: # ...until here. # This hack arises for multiple reasons but the main # one is because there are not separate API calls # for different kinds of showcases. self._metadata[type] = json_data["data"] self._models[type].setMetadata(self._metadata[type]) # Do some auto filtering # TODO: Make multiple API calls in the future to handle this if type is "packages": self._models[type].setFilter({"type": "plugin"}) if type is "authors": self._models[type].setFilter({"package_types": "material"}) self.metadataChanged.emit() if self.loadingComplete() is True: self.setViewPage("overview") return except json.decoder.JSONDecodeError: Logger.log("w", "Toolbox: Received invalid JSON for %s.", type) break else: # Ignore any operation that is not a get operation pass