def __init__(self, settings): super(KfConfig, self).__init__() self.settings = settings self.cached_kf_qlr_filename = None self.allowed_kf_services = {} self.kf_qlr_file = None self.background_category = None self.categories = None # Network self._services_network_manager = QNetworkAccessManager() self._qlr_network_manager = QNetworkAccessManager() self._services_network_manager.finished.connect( self._handle_services_response) self._qlr_network_manager.finished.connect(self._handle_qlr_response)
def networkrequest(self, nurl): global reply self.manager = QNetworkAccessManager() url = QUrl(nurl) request = QNetworkRequest(url) self.manager.finished.connect(self.handleResponse) self.manager.get(request)
def __init__(self, auth_file): logger.debug("\n================== ISOGEO API WITH QT ==================") # getting credentials : logger.debug("Getting credentials") self.utils = IsogeoUtils() self.app_creds = self.utils.credentials_loader(auth_file) self.app_id = self.app_creds.get("client_id") self.app_secrets = self.app_creds.get("client_secret") # for connection : self.naMngr = QNetworkAccessManager() self.token_url = "https://id.api.isogeo.com/oauth/token" self.request_url = ( "https://v1.api.isogeo.com/resources/search?_limit=0&_offset=0" ) # init variables : self.token = "" self.search_type = "init" self.checked_kw = {} # for ui (launch and display): logger.debug("Processing and displaying UI") self.app = QApplication(sys.argv) self.ui = AuthWidget() self.ui.resize(400, 100) self.pysdk_checking() self.api_authentification() self.ui.btn_reset.pressed.connect(self.reset) self.ui.show() self.app.exec()
def __init__(self, parent=None, iface=None): self.parent = parent self.iface = iface self.login_accepted = False self.akt_download = 0 self.all_download = 0 self.request_is_aborted = False self.nam = QNetworkAccessManager() self.nam.authenticationRequired.connect(self.set_credentials) self.nam.finished.connect(self.reply_finished)
def is_source_service_valid(self): res = False msg = {'text': '', 'level': Qgis.Warning} url = self.txt_service_endpoint.text().strip() if url: with OverrideCursor(Qt.WaitCursor): self.qgis_utils.status_bar_message_emitted.emit("Checking source service availability (this might take a while)...", 0) QCoreApplication.processEvents() if self.qgis_utils.is_connected(TEST_SERVER): nam = QNetworkAccessManager() request = QNetworkRequest(QUrl(url)) reply = nam.get(request) loop = QEventLoop() reply.finished.connect(loop.quit) loop.exec_() allData = reply.readAll() response = QTextStream(allData, QIODevice.ReadOnly) status = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) if status == 200: try: data = json.loads(response.readAll()) if 'id' in data and data['id'] == SOURCE_SERVICE_EXPECTED_ID: res = True msg['text'] = QCoreApplication.translate("SettingsDialog", "The tested service is valid to upload files!") msg['level'] = Qgis.Info else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "The tested upload service is not compatible: no valid 'id' found in response.") except json.decoder.JSONDecodeError as e: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "Response from the tested service is not compatible: not valid JSON found.") else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "There was a problem connecting to the server. The server might be down or the service cannot be reached at the given URL.") else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "There was a problem connecting to Internet.") self.qgis_utils.clear_status_bar_emitted.emit() else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "Not valid service URL to test!") return (res, msg)
def download_image(self, url): res = False img = None msg = {'text': '', 'level': Qgis.Warning} if url: self.log.logMessage("Downloading file from {}".format(url), PLUGIN_NAME, Qgis.Info) with OverrideCursor(Qt.WaitCursor): self.qgis_utils.status_bar_message_emitted.emit( "Downloading image from document repository (this might take a while)...", 0) QCoreApplication.processEvents() if self.qgis_utils.is_connected(TEST_SERVER): nam = QNetworkAccessManager() request = QNetworkRequest(QUrl(url)) reply = nam.get(request) loop = QEventLoop() reply.finished.connect(loop.quit) loop.exec_() status = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) if status == 200: res = True img = reply.readAll() else: res = False msg['text'] = QCoreApplication.translate( "SettingsDialog", "There was a problem connecting to the server. The server might be down or the service cannot be reached at the given URL." ) else: res = False msg['text'] = QCoreApplication.translate( "SettingsDialog", "There was a problem connecting to Internet.") self.qgis_utils.clear_status_bar_emitted.emit() else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "Not valid URL") if not res: self.log.logMessage(msg['text'], PLUGIN_NAME, msg['level']) return (res, img)
def save_wms_image(filename, url, layer, extent): bbox = "%f,%f,%f,%f" % (extent.xMinimum(), extent.yMinimum(), extent.xMaximum(), extent.yMaximum()) h = int(extent.height() / extent.width() * WIDTH) url = ( "%s/wms?request=GetMap&service=WMS&version=1.1.1&srs=EPSG:4326&layers=visualtests:%s&" "styles=visualtests:%s&format=image/png&width=%i&height=%i&bbox=%s" % (url, layer.name(), layer.name(), WIDTH, h, bbox)) nam = QNetworkAccessManager() reply = nam.get(QNetworkRequest(QUrl(url))) loop = QEventLoop() reply.finished.connect(loop.quit) loop.exec() img = QImage() img.loadFromData(reply.readAll()) img.save(filename)
def __init__(self, geturl_func, parseresult_func, parent=None): QObject.__init__(self, parent) self.geturl_func = geturl_func self.parseresult_func = parseresult_func self.editor = parent self.networkManager = QNetworkAccessManager() self.selectedObject = None self.isUnloaded = False self.popup = QTreeWidget(parent) #self.popup.setColumnCount(2) self.popup.setColumnCount(1) self.popup.setUniformRowHeights(True) self.popup.setRootIsDecorated(False) self.popup.setEditTriggers(QTreeWidget.NoEditTriggers) self.popup.setSelectionBehavior(QTreeWidget.SelectRows) self.popup.setFrameStyle(QFrame.Box | QFrame.Plain) self.popup.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.popup.header().hide() self.popup.installEventFilter(self) self.popup.setMouseTracking(True) #self.connect(self.popup, SIGNAL("itemClicked(QTreeWidgetItem*, int)"), # self.doneCompletion) self.popup.itemClicked.connect(self.doneCompletion) self.popup.setWindowFlags(Qt.Popup) self.popup.setFocusPolicy(Qt.NoFocus) self.popup.setFocusProxy(parent) self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(500) #self.connect(self.timer, SIGNAL("timeout()"), self.autoSuggest) self.timer.timeout.connect(self.autoSuggest) #self.connect(self.editor, SIGNAL("textEdited(QString)"), self.timer, SLOT("start()")) #self.editor.textEdited.connect( self.timer.start ) self.editor.textEdited.connect(self.timer.start) #self.editor.textChanged.connect( self.timer.start ) #self.connect(self.networkManager, SIGNAL("finished(QNetworkReply*)"), # self.handleNetworkData) self.networkManager.finished.connect(self.handleNetworkData)
def download_image(self, url): res = False img = None msg = {'text': '', 'level': Qgis.Warning} if url: self.logger.info(__name__, "Downloading file from {}".format(url)) msg_status_bar = "Downloading image from document repository (this might take a while)..." with ProcessWithStatus(msg_status_bar): if is_connected(TEST_SERVER): nam = QNetworkAccessManager() request = QNetworkRequest(QUrl(url)) reply = nam.get(request) loop = QEventLoop() reply.finished.connect(loop.quit) loop.exec_() status = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) if status == 200: res = True img = reply.readAll() else: res = False msg['text'] = QCoreApplication.translate( "SettingsDialog", "There was a problem connecting to the server. The server might be down or the service cannot be reached at the given URL." ) else: res = False msg['text'] = QCoreApplication.translate( "SettingsDialog", "There was a problem connecting to Internet.") else: res = False msg['text'] = QCoreApplication.translate("SettingsDialog", "Not valid URL") if not res: self.logger.log_message(__name__, msg['text'], msg['level']) return res, img
def _sync_get(url): global __network_manager if __network_manager is None: __network_manager = QNetworkAccessManager() __network_manager.setProxy(QgsNetworkAccessManager.instance().proxy()) pause = QEventLoop() req = QNetworkRequest(url) req.setRawHeader(b"Accept", b"application/xml") req.setRawHeader(b"Accept-Language", b"fr") reply = __network_manager.get(req) reply.finished.connect(pause.quit) is_ok = [True] def onError(self): is_ok[0] = False pause.quit() reply.error.connect(onError) pause.exec_() return reply, is_ok[0]
def _sync_get(url): global __network_manager if __network_manager is None: __network_manager = QNetworkAccessManager() __network_manager.setProxy(QgsNetworkAccessManager.instance().proxy()) pause = QEventLoop() req = QNetworkRequest(url) req.setRawHeader(b"Accept", b"application/xml") req.setRawHeader(b"Accept-Language", bytes(settings.value("default_language", "fr"), "utf8")) req.setRawHeader( b"User-Agent", bytes(settings.value("http_user_agent", plugin_name()), "utf8")) reply = __network_manager.get(req) reply.finished.connect(pause.quit) is_ok = [True] def onError(self): is_ok[0] = False pause.quit() reply.error.connect(onError) pause.exec_() return reply, is_ok[0]
address = response_data["Response"]["View"][0]["Result"][0]["Location"]["Address"]["Label"] our_layer.startEditing() address_col= our_layer.dataProvider().fieldNameIndex("address") our_layer.changeAttributeValue(fid, address_col, address) our_layer.commitChanges() QtWidgets.QMessageBox.information(None, "Success", "Location has been reverse geocoded: {}".format(address)) here_api_key = 'insert_your_here_api_key_here' our_layer = '[% @layer_id %]' QgsMessageLog.logMessage("Selected layer ID is {}".format(str(our_layer))) our_layer = QgsProject.instance().mapLayer(our_layer) fid = [% $id %] QgsMessageLog.logMessage("Selected feature ID is {}".format(str(fid))) feature = our_layer.getFeature(fid) point = feature.geometry().asPoint() lat, lng = point.y(), point.x() QgsMessageLog.logMessage("Selected coordinates are {}, {}".format(lat, lng)) manager = QNetworkAccessManager() manager.finished.connect(handle_response) do_request(manager, lat, lng, here_api_key)
def __init__(self, parent): super().__init__(parent) self.network = QNetworkAccessManager(self)
def upload_files(self, layer, field_index, features): """ Upload given features' source files to remote server and return a dict formatted as changeAttributeValues expects to update 'datos' attribute to a remote location. """ if not QSettings().value( 'Asistente-LADM_COL/sources/document_repository', False, bool): self.message_with_duration_emitted.emit( QCoreApplication.translate( "SourceHandler", "The source files were not uploaded to the document repository because you have that option unchecked. You can still upload the source files later using the 'Upload Pending Source Files' menu." ), Qgis.Info, 10) return dict() # Test if we have Internet connection and a valid service dlg = self.qgis_utils.get_settings_dialog() res, msg = dlg.is_source_service_valid() if not res: msg['text'] = QCoreApplication.translate( "SourceHandler", "No file could be uploaded to the document repository. You can do it later from the 'Upload Pending Source Files' menu. Reason: {}" ).format(msg['text']) self.message_with_duration_emitted.emit( msg['text'], Qgis.Info, 20) # The data is still saved, so always show Info msg return dict() file_features = [ feature for feature in features if not feature[field_index] == NULL and os.path.isfile(feature[field_index]) ] total = len(features) not_found = total - len(file_features) upload_dialog = UploadProgressDialog(len(file_features), not_found) upload_dialog.show() count = 0 upload_errors = 0 new_values = dict() for feature in file_features: data_url = feature[field_index] file_name = os.path.basename(data_url) nam = QNetworkAccessManager() #reply.downloadProgress.connect(upload_dialog.update_current_progress) multiPart = QHttpMultiPart(QHttpMultiPart.FormDataType) textPart = QHttpPart() textPart.setHeader(QNetworkRequest.ContentDispositionHeader, QVariant("form-data; name=\"driver\"")) textPart.setBody(QByteArray().append('Local')) filePart = QHttpPart() filePart.setHeader( QNetworkRequest.ContentDispositionHeader, QVariant("form-data; name=\"file\"; filename=\"{}\"".format( file_name))) file = QFile(data_url) file.open(QIODevice.ReadOnly) filePart.setBodyDevice(file) file.setParent( multiPart ) # we cannot delete the file now, so delete it with the multiPart multiPart.append(filePart) multiPart.append(textPart) service_url = '/'.join([ QSettings().value( 'Asistente-LADM_COL/sources/service_endpoint', DEFAULT_ENDPOINT_SOURCE_SERVICE), SOURCE_SERVICE_UPLOAD_SUFFIX ]) request = QNetworkRequest(QUrl(service_url)) reply = nam.post(request, multiPart) #reply.uploadProgress.connect(upload_dialog.update_current_progress) reply.error.connect(self.error_returned) multiPart.setParent(reply) # We'll block execution until we get response from the server loop = QEventLoop() reply.finished.connect(loop.quit) loop.exec_() response = reply.readAll() data = QTextStream(response, QIODevice.ReadOnly) content = data.readAll() if content is None: self.log.logMessage( "There was an error uploading file '{}'".format(data_url), PLUGIN_NAME, Qgis.Critical) upload_errors += 1 continue try: response = json.loads(content) except json.decoder.JSONDecodeError: self.log.logMessage( "Couldn't parse JSON response from server for file '{}'!!!" .format(data_url), PLUGIN_NAME, Qgis.Critical) upload_errors += 1 continue if 'error' in response: self.log.logMessage( "STATUS: {}. ERROR: {} MESSAGE: {} FILE: {}".format( response['status'], response['error'], response['message'], data_url), PLUGIN_NAME, Qgis.Critical) upload_errors += 1 continue reply.deleteLater() if 'url' not in response: self.log.logMessage( "'url' attribute not found in JSON response for file '{}'!" .format(data_url), PLUGIN_NAME, Qgis.Critical) upload_errors += 1 continue url = self.get_file_url(response['url']) new_values[feature.id()] = {field_index: url} count += 1 upload_dialog.update_total_progress(count) if not_found > 0: self.message_with_duration_emitted.emit( QCoreApplication.translate( "SourceHandler", "{} out of {} records {} not uploaded to the document repository because {} file path is NULL or it couldn't be found in the local disk!" ).format( not_found, total, QCoreApplication.translate("SourceHandler", "was") if not_found == 1 else QCoreApplication.translate( "SourceHandler", "were"), QCoreApplication.translate("SourceHandler", "its") if not_found == 1 else QCoreApplication.translate( "SourceHandler", "their")), Qgis.Info, 0) if len(new_values): self.message_with_duration_emitted.emit( QCoreApplication.translate( "SourceHandler", "{} out of {} files {} uploaded to the document repository and {} remote location stored in the database!" ).format( len(new_values), total, QCoreApplication.translate("SourceHandler", "was") if len(new_values) == 1 else QCoreApplication.translate( "SourceHandler", "were"), QCoreApplication.translate("SourceHandler", "its") if len(new_values) == 1 else QCoreApplication.translate( "SourceHandler", "their")), Qgis.Info, 0) if upload_errors: self.message_with_duration_emitted.emit( QCoreApplication.translate( "SourceHandler", "{} out of {} files could not be uploaded to the document repository because of upload errors! See log for details." ).format(upload_errors, total), Qgis.Info, 0) return new_values
def __init__(self, url, method='GET', **data): self.manager = QNetworkAccessManager() self.method = method self.url = QUrl(url) self.request = QNetworkRequest(self.url)
def __init__(self): super().__init__() self.isKill = None self.responseAllFinished = None self.nam = QNetworkAccessManager(self) self.nam.finished.connect( self.replyFinished )