def download(self, sql): apiUrl = "http://{}.cartodb.com/api/v2/sql?api_key={}&format=spatialite&q={}".format( self.cartodbUser, self.apiKey, sql ) url = QUrl(apiUrl) request = self._getRequest(url) def finished(reply): tempdir = tempfile.tempdir if tempdir is None: tempdir = tempfile.mkdtemp() tf = tempfile.NamedTemporaryFile(delete=False) sqlite = QFile(tf.name) tf.close() if sqlite.open(QIODevice.WriteOnly): sqlite.write(reply.readAll()) sqlite.close() self.fetchContent.emit(tf.name) else: self.error.emit("Error saving downloaded file") manager = QNetworkAccessManager() manager.finished.connect(finished) reply = manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def waitForSignal(signal, message="", timeout=0): """Waits (max timeout msecs if given) for a signal to be emitted. It the waiting lasts more than 2 seconds, a progress dialog is displayed with the message. Returns True if the signal was emitted. Return False if the wait timed out or the dialog was canceled by the user. """ loop = QEventLoop() dlg = QProgressDialog(minimum=0, maximum=0, labelText=message) dlg.setWindowTitle(appinfo.appname) dlg.setWindowModality(Qt.ApplicationModal) QTimer.singleShot(2000, dlg.show) dlg.canceled.connect(loop.quit) if timeout: QTimer.singleShot(timeout, dlg.cancel) stop = lambda: loop.quit() signal.connect(stop) loop.exec_() signal.disconnect(stop) dlg.hide() dlg.deleteLater() return not dlg.wasCanceled()
def call_method(self, method, *args, **kwargs): """Call a method.""" callback = kwargs.get('callback') if callback is not None: super(QtMessageBusConnection, self).call_method(method, *args, **kwargs) return replies = [] loop = QEventLoop() def _store_reply(message): replies.append(message) loop.quit() kwargs['callback'] = _store_reply super(QtMessageBusConnection, self).call_method(method, *args, **kwargs) mask = QEventLoop.ExcludeUserInputEvents | QEventLoop.WaitForMoreEvents while True: loop.processEvents(mask) if replies: break reply = replies[0] if 'error' in reply: raise MessageBusError(reply['error']['code'], reply['error'].get('data')) return reply.get('result')
def quit(self): loop = QEventLoop() reply = self._make_request('quit') reply.finished.connect(loop.quit) loop.exec_() QThread.quit(self)
def run(self, installSignalHandlers=True): if self._ownApp: self._blockApp = self.qApp else: self._blockApp = QEventLoop() self.runReturn() self._blockApp.exec_()
def load(self): worker = CartoDBPluginWorker(self, 'loadLayer') worker.error.connect(self.workerError) self.loop = QEventLoop() worker.finished.connect(self.workerFinished) worker.start() self.loop.exec_()
def getUserTables(self, page=1, per_page=20, shared='yes', returnDict=True): self.returnDict = returnDict payload = { 'tag_name': '', 'q': '', 'page': page, 'type': '', 'exclude_shared': 'false', 'per_page': per_page, 'tags': '', 'shared': shared, 'locked': 'false', 'only_liked': 'false', 'order': 'name', 'types': 'table' } url = QUrl(self.apiUrl + "viz?api_key={}&{}".format(self.apiKey, urllib.urlencode(payload))) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def getUserTables(self, page=1, per_page=20, shared="yes", returnDict=True): self.returnDict = returnDict payload = { "tag_name": "", "q": "", "page": page, "type": "", "exclude_shared": "false", "per_page": per_page, "tags": "", "shared": shared, "locked": "false", "only_liked": "false", "order": "name", "types": "table", } url = QUrl(self.apiUrl + "viz?api_key={}&{}".format(self.apiKey, urllib.urlencode(payload))) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def OeQ_wait_for_file(filepath,timeout=10000): """Block loop until signal emitted, or timeout (ms) elapses.""" from PyQt4.QtCore import QEventLoop,QTimer from os.path import isfile import platform import os if platform.system() == 'Darwin': return True if isfile(filepath): return True loop = QEventLoop() timer=QTimer() file_result = [True] # def check_file(testpath): if isfile(testpath): timer.stop() loop.quit() # timer.timeout.connect(lambda: check_file(filepath)) timer.setSingleShot(False) timer.start(500) # def timed_out(file_result_flag): file_result_flag[0]=False loop.quit() # if timeout >500: timer.singleShot(timeout,lambda: timed_out(file_result)) loop.exec_() return file_result[0]
def OeQ_wait_for_renderer(timeout=10000): """Block loop until signal emitted, or timeout (ms) elapses.""" from PyQt4.QtCore import QEventLoop,QTimer #print 'wait for renderer...', # function call if action timed out def timed_out(render_result_flag): render_result_flag[0]=False loop.quit() #define loop loop = QEventLoop() #define Timer timer=QTimer() #define render_result render_result = [True] OeQ_wait(2) #check wether Canvas is drawing if iface.mapCanvas().isDrawing(): #connect mapCanvasRefreshed and renderComplete events to quit loop iface.mapCanvas().renderComplete.connect(loop.quit) iface.mapCanvas().mapCanvasRefreshed.connect(loop.quit) # if a timeout is defined and other than 0 if bool(timeout): # start timer timer.singleShot(timeout,lambda: timed_out(render_result)) #and jump into the loop loop.exec_() #disconnect after loop has quit iface.mapCanvas().mapCanvasRefreshed.disconnect(loop.quit) iface.mapCanvas().renderComplete.disconnect(loop.quit) #print 'Done' return render_result[0]
def f2(): future = ac.start(em2.g, lambda x: x, QThread.currentThread()) # The doneSignal won't be processed without an event loop. A # thread pool doesn't create one, so make our own to run ``g``. qe = QEventLoop() future._signalInvoker.doneSignal.connect(qe.exit) qe.exec_()
def query(self, query): """ Perform a nominatim query @param query: Query to execute @type query: str @raise NetWorkErrorException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url) query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('q', query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: return json.loads(self.data) else: raise NetWorkErrorException(suffix="Nominatim API")
def download_file(self, url, path_file): """ download function :param url: url path of file :param path_file: path to save file :return: """ self.file_install = path_file self.url = url loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(lambda: loop.exit(1)) timer.start(100000) # 10 second time-out # req = QNetworkRequest(QUrl('https://www.python.org/')) req = QNetworkRequest(QUrl(url)) result = self.manager.get(req) result.finished.connect(lambda: self.fin_req(loop, result)) self.print_('fetching request...', self.dbg) if loop.exec_() == 0: timer.stop() self.print_( '{} is received: {}'.format(os.path.basename(path_file), result.readAll().count()), self.dbg) else: self.print_('request timed-out')
def _processPendingEvents(): """Process pending application events.""" # Create an event loop to run in. Otherwise, we need to use the # QApplication main loop, which may already be running and therefore # unusable. qe = QEventLoop() # Create a single-shot timer. Could use QTimer.singleShot(), # but can't cancel this / disconnect it. timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(qe.quit) timer.start(1) # Wait for an emitted signal. qe.exec_() # Clean up: don't allow the timer to call qe.quit after this # function exits, which would produce "interesting" behavior. timer.stop() # Stopping the timer may not cancel timeout signals in the # event queue. Disconnect the signal to be sure that loop # will never receive a timeout after the function exits. timer.timeout.disconnect(qe.quit)
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert isinstance(self.task.thread(), _TaskDepotThread) QMetaObject.invokeMethod(self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread())) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. # TODO: If the task encounters an critical error it might not emit # these signals and this Runnable will never complete. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def getUserTables(self, page=1, per_page=20, shared='yes', returnDict=True): self.returnDict = returnDict payload = { 'tag_name': '', 'q': '', 'page': page, 'type': '', 'exclude_shared': 'false', 'per_page': per_page, 'tags': '', 'shared': shared, 'locked': 'false', 'only_liked': 'false', 'order': 'name', 'types': 'table' } url = QUrl( self.apiUrl + "viz?api_key={}&{}".format(self.apiKey, urllib.urlencode(payload))) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def get(self, url=None, script=None, key=None): """Load given url in webkit and return html when loaded """ self.base_url = self.base_url or url # set base URL if not set html = self.cache.get(key) if html: if self.debug: print 'load cache', key self.setHtml(html, QUrl(self.base_url)) elif url: self.load(QUrl(url)) elif script: self.js(script) loop = QEventLoop() timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) self.loadFinished.connect(loop.quit) timer.start(self.timeout * 1000) loop.exec_() # delay here until download finished or timeout if timer.isActive(): # downloaded successfully timer.stop() html = self.current_html() if key: self.cache[key] = html self.inject_jquery() else: # didn't download in time print 'Download timeout' html = '' return html
def run(self): time = QTime() eventLoop = QEventLoop() self.m_bStop = False # log.debug("Запускаем поток") #if not self.initThread(): #return while not self.m_bStop: self.m_nTactCounter += 1 # Добавить обнуление при переполнении time.start() eventLoop.processEvents() if not self.workThread(): self.m_bStop = True return workTime = time.elapsed() if 0 <= workTime < self.m_nTact: self.msleep(self.m_nTact - workTime) else: self.msleep(0) eventLoop.processEvents() self.exitThread()
def __sync_request(self, url): _url = QUrl(url) _request = QNetworkRequest(_url) self.__replies.append(_request) QgsNetworkAccessManager.instance().sslErrors.connect(self.__supress_ssl_errors) _reply = QgsNetworkAccessManager.instance().get(_request) # wait loop = QEventLoop() _reply.finished.connect(loop.quit) loop.exec_() _reply.finished.disconnect(loop.quit) QgsNetworkAccessManager.instance().sslErrors.disconnect(self.__supress_ssl_errors) loop = None error = _reply.error() if error != QNetworkReply.NoError: raise Exception(error) result_code = _reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) result = _reply.readAll() self.__replies.append(_reply) _reply.deleteLater() if result_code in [301, 302, 307]: redirect_url = _reply.attribute(QNetworkRequest.RedirectionTargetAttribute) return self.__sync_request(redirect_url) else: return result
def OeQ_wait_for_renderer(timeout=10000): """Block loop until signal emitted, or timeout (ms) elapses.""" from PyQt4.QtCore import QEventLoop, QTimer #print 'wait for renderer...', # function call if action timed out def timed_out(render_result_flag): render_result_flag[0] = False loop.quit() #define loop loop = QEventLoop() #define Timer timer = QTimer() #define render_result render_result = [True] OeQ_wait(2) #check wether Canvas is drawing if iface.mapCanvas().isDrawing(): #connect mapCanvasRefreshed and renderComplete events to quit loop iface.mapCanvas().renderComplete.connect(loop.quit) iface.mapCanvas().mapCanvasRefreshed.connect(loop.quit) # if a timeout is defined and other than 0 if bool(timeout): # start timer timer.singleShot(timeout, lambda: timed_out(render_result)) #and jump into the loop loop.exec_() #disconnect after loop has quit iface.mapCanvas().mapCanvasRefreshed.disconnect(loop.quit) iface.mapCanvas().renderComplete.disconnect(loop.quit) #print 'Done' return render_result[0]
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert self.task.thread() is _TaskDepotThread.instance() QMetaObject.invokeMethod( self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread()) ) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def download(self, sql): apiUrl = 'http://{}.{}/api/v2/sql?api_key={}&format=spatialite&q={}'.format( self.cartodbUser, self.hostname, self.apiKey, sql) url = QUrl(apiUrl) request = self._getRequest(url) def finished(reply): tempdir = tempfile.tempdir if tempdir is None: tempdir = tempfile.mkdtemp() tf = tempfile.NamedTemporaryFile(delete=False) sqlite = QFile(tf.name) tf.close() if (sqlite.open(QIODevice.WriteOnly)): sqlite.write(reply.readAll()) sqlite.close() self.fetchContent.emit(tf.name) else: self.error.emit('Error saving downloaded file') manager = QNetworkAccessManager() manager.finished.connect(finished) reply = manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def __sync_request(self, url): _url = QUrl(url) _request = QNetworkRequest(_url) self.__replies.append(_request) QgsNetworkAccessManager.instance().sslErrors.connect( self.__supress_ssl_errors) _reply = QgsNetworkAccessManager.instance().get(_request) # wait loop = QEventLoop() _reply.finished.connect(loop.quit) loop.exec_() _reply.finished.disconnect(loop.quit) QgsNetworkAccessManager.instance().sslErrors.disconnect( self.__supress_ssl_errors) loop = None error = _reply.error() if error != QNetworkReply.NoError: raise Exception(error) result_code = _reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) result = _reply.readAll() self.__replies.append(_reply) _reply.deleteLater() if result_code in [301, 302, 307]: redirect_url = _reply.attribute( QNetworkRequest.RedirectionTargetAttribute) return self.__sync_request(redirect_url) else: return result
def cbUserData(self, data): if 'error' in data: # TODO Create image for error self.nameLB.setText( "<html><head/><body><p><span style=\" text-decoration: underline; color:red;\">error</span></p></body></html>" ) self.error.emit(data['error']) return self.currentUserData = data self.settings.setValue('/CartoDBPlugin/selected', self.currentUser) manager = QNetworkAccessManager() manager.finished.connect(self.returnAvatar) if 's3.amazonaws.com' in data['avatar_url']: imageUrl = QUrl(data['avatar_url']) else: imageUrl = QUrl('http:' + data['avatar_url']) request = QNetworkRequest(imageUrl) request.setRawHeader('User-Agent', 'QGIS 2.x') reply = manager.get(request) loop = QEventLoop() reply.finished.connect(loop.exit) loop.exec_()
class CartoDBLayerWorker(QObject): finished = pyqtSignal(CartoDBLayer) error = pyqtSignal(Exception, basestring) def __init__(self, iface, tableName, owner=None, dlg=None, sql=None, filterByExtent=False, readonly=False, multiuser=False): QObject.__init__(self) self.iface = iface self.owner = owner self.tableName = tableName self.readonly = readonly self.multiuser = multiuser self.dlg = dlg self.sql = sql self.filterByExtent = filterByExtent self.loop = None def load(self): worker = CartoDBPluginWorker(self, 'loadLayer') worker.error.connect(self.workerError) self.loop = QEventLoop() worker.finished.connect(self.workerFinished) worker.start() self.loop.exec_() @pyqtSlot(str) def _loadData(self, spatiaLite): layer = CartoDBLayer(self.iface, self.tableName, self.dlg.currentUser, self.dlg.currentApiKey, self.owner, self.sql, spatiaLite=spatiaLite, readonly=self.readonly, multiuser=self.multiuser) self.finished.emit(layer) @pyqtSlot() def loadLayer(self): if self.sql is None: sql = 'SELECT * FROM ' + ((self.owner + '.') if self.owner != self.dlg.currentUser else '') + self.tableName if self.filterByExtent: extent = self.iface.mapCanvas().extent() sql = sql + " WHERE ST_Intersects(ST_GeometryFromText('{}', 4326), the_geom)".format(extent.asWktPolygon()) else: sql = self.sql cartoDBApi = CartoDBApi(self.dlg.currentUser, self.dlg.currentApiKey) cartoDBApi.fetchContent.connect(self._loadData) cartoDBApi.download(sql) # cartoDBApi.getDataFromTable(sql, False) # geoJSON = self._loadData() """ On worker has finished """ def workerFinished(self, ret): QgsMessageLog.logMessage('Task finished:\n' + str(ret), 'CartoDB Plugin', QgsMessageLog.INFO) self.loop.exit() """ On worker error """ def workerError(self, e, exception_string): QgsMessageLog.logMessage('Worker thread raised an exception: {} - {}\n'.format(exception_string, str(e)), 'CartoDB Plugin', QgsMessageLog.CRITICAL)
def wait_input(self): """Wait for input (raw_input)""" self.input_data = None # If shell is closed, None will be returned self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None return self.input_data
def wait_input(self, prompt=''): """Wait for input (raw_input support)""" self.new_prompt(prompt) self.setFocus() self.input_mode = True self.input_loop = QEventLoop() self.input_loop.exec_() self.input_loop = None
def exec_(self): self.show() e = QEventLoop() self.eventLoop = e e.exec_() self.eventLoop = None
def _createWebAppCompiled(n): from pubsub import pub def endWriteWebAppListener(success, reason): from pubsub import pub pub.unsubscribe(endWriteWebAppListener, topics.endWriteWebApp) loop.exit() loop = QEventLoop() pub.subscribe(endWriteWebAppListener , topics.endWriteWebApp) _createWebApp(n, False) loop.exec_(flags = QEventLoop.ExcludeUserInputEvents)
def run(self): self.eventLoop = QEventLoop() self.eventLoop.processEvents() QObject.connect(self._call, SIGNAL("finished(QString)"), lambda str: self.eventLoop.quit()) QMetaObject.invokeMethod( self._call, "moveToAndInit", Qt.QueuedConnection, Q_ARG("PyQt_PyObject", QThread.currentThread())) self.eventLoop.processEvents() self.eventLoop.exec_()
def __enter__(self): # Create an event loop to run in. Otherwise, we need to use the papp # (QApplication) main loop, which may already be running and therefore # unusable. self.qe = QEventLoop() # Connect both signals to a slot which quits the event loop. self.signal.connect(self.signalSlot) return self
def quit(self): if self.io_conn and self.io_conn.state() == QTcpSocket.ConnectedState: loop = QEventLoop() self.io_conn.disconnected.connect(loop.quit) self.io_conn.disconnectFromHost() self.log.debug("Entered disconnect state...") if self.io_conn.state() == QTcpSocket.ConnectedState: loop.exec_() self.log.info("Done") Connection.quit(self)
def request(self, url): ''' prepare the request and return the result of the reply ''' request = QNetworkRequest(QUrl(url)) reply = self.manager.get(request) reply.deleteLater() evloop = QEventLoop() reply.finished.connect(evloop.quit) evloop.exec_(QEventLoop.ExcludeUserInputEvents) return unicode(reply.readAll())
def updateViz(self, viz, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "viz/{}?api_key={}".format(viz["id"], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(viz)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def checkUploadStatus(self, id, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "imports/{}/?api_key={}".format(id, self.apiKey)) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def updateLayerInMap(self, mapId, layer, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "maps/{}/layers/{}?api_key={}".format(mapId, layer["id"], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(layer)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def getLayersMap(self, mapId, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "maps/{}/layers?api_key={}".format(mapId, self.apiKey)) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def getUserDetails(self, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "users/{}/?api_key={}".format(self.cartodbUser, self.apiKey)) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def _wait_signal(signal, timeout=None): """Block loop until signal emitted, or timeout (ms) elapses.""" # http://jdreaver.com/posts/2014-07-03-waiting-for-signals-pyside-pyqt.html loop = QEventLoop() signal.connect(loop.quit) yield if timeout is not None: QTimer.singleShot(timeout, loop.quit) loop.exec_()
def getDataFromTable(self, sql, returnDict=True): self.returnDict = returnDict apiUrl = 'http://{}.cartodb.com/api/v2/sql?api_key={}&format=GeoJSON&q={}'.format(self.cartodbUser, self.apiKey, sql) url = QUrl(apiUrl) request = self._getRequest(url) reply = self.manager.get(request) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def __init__(self, word, dico, combo1_index, combo2_index, combo2_text, wordclass): self.word = word self.dico = dico self.combo1_index = combo1_index self.combo2_index = combo2_index self.combo2_text = combo2_text self.wordclass = wordclass self.manager = QNetworkAccessManager() self.manager.finished.connect(self.reply_finished) self.loop = QEventLoop() self.manager.finished.connect(self.loop.quit) self._reply = ""
def get(self, url, html=None, headers=None, data=None): """Load given url in webkit and return html when loaded url: the URL to load html: optional HTML to set instead of downloading headers: the headers to attach to the request data: the data to POST """ if isinstance(url, basestring): # convert string to Qt's URL object url = QUrl(url) if html: # load pre downloaded HTML self.setContent(html, baseUrl=url) return html t1 = time() loop = QEventLoop() self.loadFinished.connect(loop.quit) # need to make network request request = QNetworkRequest(url) if headers: # add headers to request when defined for header, value in headers: request.setRawHeader(header, value) self.page().networkAccessManager().main_url = url request.setOriginatingObject(self) if data: # POST request super(Browser, self).load(request, QNetworkAccessManager.PostOperation, data) else: # GET request super(Browser, self).load(request) # set a timeout on the download loop timer = QTimer() timer.setSingleShot(True) timer.timeout.connect(loop.quit) timer.start(self.timeout * 1000) loop.exec_() # delay here until download finished or timeout if timer.isActive(): # downloaded successfully timer.stop() parsed_html = self.current_html() self.wait(self.delay - (time() - t1)) else: # did not download in time common.logger.debug('Timed out: {}'.format(url.toString())) parsed_html = '' return parsed_html
def updateLayerInMap(self, mapId, layer, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "maps/{}/layers/{}?api_key={}".format( mapId, layer['id'], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(layer)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def updateViz(self, viz, returnDict=True): self.returnDict = returnDict url = QUrl(self.apiUrl + "viz/{}?api_key={}".format(viz['id'], self.apiKey)) request = self._getRequest(url) reply = self.manager.put(request, json.dumps(viz)) loop = QEventLoop() reply.downloadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def __init__(self, path): self.data = [] if os.path.exists(path): with open(path) as f: self.data = f.readlines() elif path.startswith("http"): url = QUrl(path) loop = QEventLoop() manager = QNetworkAccessManager() request = QNetworkRequest(url) reply = manager.get(request) reply.finished.connect(loop.exit) loop.exec_() if reply.error() == QNetworkReply.NoError: self.data = reply.readAll().data().decode('utf-8').split("\n")
def upload(self, filePath, returnDict=True): self.returnDict = returnDict file = QFile(filePath) file.open(QFile.ReadOnly) url = QUrl(self.apiUrl + "imports/?api_key={}".format(self.apiKey)) files = {"file": file} multipart = self._createMultipart(files=files) request = QNetworkRequest(url) request.setHeader(QNetworkRequest.ContentTypeHeader, "multipart/form-data; boundary=%s" % multipart.boundary()) request.setRawHeader("User-Agent", "QGISCartoDB 0.2.x") reply = self.manager.post(request, multipart) loop = QEventLoop() reply.uploadProgress.connect(self.progressCB) reply.error.connect(self._error) reply.finished.connect(loop.exit) loop.exec_()
def query(self, query): """ Perform a nominatim query @param query: Query to execute @type query: str @raise NetWorkErrorException @return: the result of the query @rtype: str """ url_query = QUrl(self.__url) query = QUrl.toPercentEncoding(query) url_query.addEncodedQueryItem('q', query) url_query.addQueryItem('info', 'QgisQuickOSMPlugin') url_query.setPort(80) proxy = get_proxy() if proxy: self.network.setProxy(proxy) request = QNetworkRequest(url_query) request.setRawHeader("User-Agent", "QuickOSM") self.network_reply = self.network.get(request) self.loop = QEventLoop() self.network.finished.connect(self._end_of_request) self.loop.exec_() if self.network_reply.error() == QNetworkReply.NoError: return json.loads(self.data) else: raise NetWorkErrorException(suffix="Nominatim API")
def run(self): """ Reimplemented from `QRunnable.run` """ self.eventLoop = QEventLoop() self.eventLoop.processEvents() # Move the task to the current thread so it's events, signals, slots # are triggered from this thread. assert isinstance(self.task.thread(), _TaskDepotThread) QMetaObject.invokeMethod( self.task.thread(), "transfer", Qt.BlockingQueuedConnection, Q_ARG(object, self.task), Q_ARG(object, QThread.currentThread()) ) self.eventLoop.processEvents() # Schedule task.run from the event loop. self.task.start() # Quit the loop and exit when task finishes or is cancelled. # TODO: If the task encounters an critical error it might not emit # these signals and this Runnable will never complete. self.task.finished.connect(self.eventLoop.quit) self.task.cancelled.connect(self.eventLoop.quit) self.eventLoop.exec_()
def wait_signal(signal, timeout=1): """Block loop until signal emitted, or timeout (s) elapses.""" loop = QEventLoop() signal.connect(loop.quit) yield timed_out = [] if timeout is not None: def quit_with_error(): timed_out.append(1) loop.quit() QTimer.singleShot(timeout * 1000, quit_with_error) loop.exec_() if timed_out: assert False, "Timeout while waiting for %s" % signal
def __init__(self): QObject.__init__(self) self.basewfs = "http://geo.zaanstad.nl/geoserver/wfs?request=GetFeature&version=2.0.0&outputFormat=JSON" self.manager = QNetworkAccessManager(self) self.timer = QTimer() self.loop = QEventLoop() self.reply = None
def upload(self, filePath, returnDict=True): self.returnDict = returnDict file = QFile(filePath) file.open(QFile.ReadOnly) apiUrl = 'https://{}.cartodb.com/api/v1/imports/?api_key={}'.format(self.cartodbUser, self.apiKey) url = QUrl(apiUrl) files = {'file': file} multipart = self._createMultipart(files=files) request = QNetworkRequest(url) request.setHeader(QNetworkRequest.ContentTypeHeader, 'multipart/form-data; boundary=%s' % multipart.boundary()) request.setRawHeader('User-Agent', 'QGIS 2.x') reply = self.manager.post(request, multipart) loop = QEventLoop() reply.uploadProgress.connect(self.progressCB) reply.error.connect(self.error) reply.finished.connect(loop.exit) loop.exec_()