def _doUpload(self): if self.current_track is None or self._aborted: return track, track_type = self.current_track self.statusMessage.emit('Uploading {0}'.format(track['name'])) log.debug('Sending upload request (%s)', track['name']) # data_fields, data = bryton_gpx_to_strava_json(track['gpx']) data = tcx.bryton_gpx_to_tcx(track['gpx'], activity_type=track_type, pretty=False, device=self.device_info) req = QNetworkRequest(QUrl(self.UPLOAD)) req.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") # d2 = json.loads(open('tmp/test.json').read()) # d2['token'] = self.auth_token # self.reply = self.network_manager.post(req, json.dumps(d2)) self.reply = self.network_manager.post(req, json.dumps({ 'token' : self.auth_token, 'type' : 'tcx', 'data' : data, 'activity_type' : track_type, })) self.reply.finished.connect(self._onUploaded)
def read(self, **kwargs): self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished) params = [] try: queryable = kwargs["queryable"] params.append({"queryable": queryable}) queryableList = QString(queryable).split(",") except KeyError: pass for key, value in kwargs.items(): if QString(key).split("__")[0] in queryableList: params.append({key: value}) url = "%s/stakeholders?" % self.host for p in params: url = "%s%s=%s&" % (url, p.keys()[0], p.values()[0]) qUrl = QUrl(url) # Create a new request request = QNetworkRequest(qUrl) request.setRawHeader("Authorization", self.login) request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.get(request) return url
def get_data(self): request = QNetworkRequest(QUrl(self.config.url)) request.setHeader(QNetworkRequest.ContentTypeHeader, 'text/xml') # or? "text/xml; charset=utf-8" reply = self.network_manager.post(request, self.xml()) extension = '.zip' if self.config.jrodos_format == 'application/json': extension = '.json' filename = self.config.output_dir + '/' + unicode(self.column) + '_' + unicode( self.config.jrodos_verticals) + extension reply.finished.connect(partial(self._data_retrieved, reply, filename))
def post(self, mgr , url , datas): request = QNetworkRequest(QtCore.QUrl(url)) request.setHeader(QNetworkRequest.ContentTypeHeader,"application/x-www-form-urlencoded") self.reply = mgr.post(request , datas) self.reply.finished.connect(self.replyfinished) self.reply.readyRead.connect(self.readyRead) return self.reply
def authenticate(self, username, password): log.debug('Sending auth request') req = QNetworkRequest(QUrl(self.LOGIN)) req.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded") self.reply = self.network_manager.post(req, urllib.urlencode({ 'email' : username, 'password' : password, })) self.reply.finished.connect(self._onAuthenticated)
class SettingsProtocol(QObject): readSignal = pyqtSignal(bool, int, QString) def __init__(self, host, user, password): QObject.__init__(self) # Set the host self.host = host # Create a base64 encoded credential string from user name and password. # This is required for the HTTP basic access authentication, compare # also http://en.wikipedia.org/wiki/Basic_access_authentication self.userlogin = "******" % (user, password) self.login = "******" + QByteArray(self.userlogin).toBase64() # Create a new QNetworkAccessManager and connect it to the # authenticationRequired signal self.manager = QNetworkAccessManager(self) # self.connect(self.manager, SIGNAL("authenticationRequired( QNetworkReply*, QAuthenticator* )"), self.slotAuthenticationRequired) def read(self): self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished) url = "%s/config/geometrytaggroups" % self.host qUrl = QUrl(url) self.request = QNetworkRequest(qUrl) self.request.setRawHeader("Authorization", self.login) self.request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.get(self.request) return url def readRequestFinished(self, reply): # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute).toString()) data = reply.readAll() # Check the status code see also http://en.wikipedia.org/wiki/HTTP_status_code # In case of a successful upload we get a 201 status code back and the # "stylePosted" signal is emitted with the first parameter set to True. # If the query didn't succeed, the status code is 4xx indicating that # the host was not found, the authentication failed or a forbidden # action in case a style with the same name already exists. It's up to # the receiver to handle these status codes. self.readSignal.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, QString(data))
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 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_()
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 get_data(self, param='Quantities', arg0=False, arg1=False): """ :param param: 'Quantities', 'Substances', 'Units' or 'MeasuredCombinations' :param arg0: start time: '2019-03-06T00:00:00.000Z' (only 'MeasuredCombinations') :param arg1: end time '2019-03-06T12:00:00.000Z' (only 'MeasuredCombinations') :return: result in json """ data = """<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://service.ws.calnet.rivm.nl/"> <soap:Header/> <soap:Body> <ws:get%s /> </soap:Body> </soap:Envelope>""" % param if param == 'MeasuredCombinations': data = """<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://service.ws.calnet.rivm.nl/"> <soap:Header/> <soap:Body> <ws:getMeasuredCombinations> <arg0>%s</arg0> <arg1>%s</arg1> </ws:getMeasuredCombinations> </soap:Body> </soap:Envelope>""" % (self.config.start_datetime, self.config.end_datetime) print(data) request = QNetworkRequest(QUrl(self.config.url)) request.setHeader(QNetworkRequest.ContentTypeHeader, "application/soap+xml") # or? "text/xml; charset=utf-8" reply = self.network_manager.post(request, data) reply.finished.connect(partial(self._data_retrieved, reply)) # this part is needed to be sure we do not return immidiatly # while not reply.isFinished(): # #QCoreApplication.processEvents() # from PyQt4.QtCore import QEventLoop # QCoreApplication.processEvents(QEventLoop.AllEvents, 100 )
def loadModel(self): imd = None try: loader = ModelLoader(self.ui.mDataLineEdit.text()) models = loader.detect_models() model_names = map(lambda m: m.name, models) self._log_output("Looking up models: " + ', '.join(model_names)) ili = loader.gen_lookup_ili() qDebug(ili) wpsreq = self._create_wps_request(ili) url = self.ui.mIlisMetaUrlLineEdit.text() req = QNetworkRequest(QtCore.QUrl(url)) req.setHeader(QNetworkRequest.ContentTypeHeader, 'application/xml') reply = QgsNetworkAccessManager.instance().post(req, wpsreq) # Wait for reply or timeout loop = QEventLoop() reply.finished.connect(loop.quit) QTimer.singleShot(15000, reply.abort) loop.exec_() if reply.isFinished() and reply.error() == QNetworkReply.NoError: result = reply.readAll() imd = self._parse_wps_response(result) except: qDebug("Exception during IlisModel download") if imd is None: self._show_log_window() QgsMessageLog.logMessage( "Couldn't download Ilismeta model", "Interlis", QgsMessageLog.WARNING) self.ui.mModelLineEdit.setText("") else: fh, imdfn = tempfile.mkstemp(suffix='.imd') os.close(fh) with codecs.open(imdfn, "w", encoding='utf-8') as file: file.write(imd) self.ui.mModelLineEdit.setText(imdfn)
def add(self, stakeholder): self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished) url = "%s/stakeholders" % self.host qurl = QUrl(url) # Create a new request request = QNetworkRequest(qurl) request.setRawHeader("Authorization", self.login) request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") wrapperObj = {} if len(stakeholder) > 0: wrapperObj["stakeholders"] = [s.createDiff(None) for s in stakeholder] else: wrapperObj["stakeholders"] = [stakeholder.createDiff(None)] rawBody = json.dumps(wrapperObj, sort_keys=True, indent=4 * " ") self.manager.post(request, rawBody) return url, rawBody
def run(self): xx = str(self.__xx) yy = str(self.__yy) if abs(float(xx)) > 180 or abs(float(yy)) > 90: QgsMessageLog.logMessage( self.tr('Worker: %s, %s are wrong coords!') % (xx, yy), self.tr('OSMInfo'), QgsMessageLog.INFO ) self.gotError.emit(self.tr('Worker: %s, %s are wrong coords!') % (xx, yy)) return url = 'http://overpass-api.de/api/interpreter' request = QNetworkRequest(QUrl(url)) request.setHeader(QNetworkRequest.ContentTypeHeader, 'application/x-www-form-urlencoded'); qnam = QgsNetworkAccessManager.instance() # around request dist = PluginSettings.distance_value() request_data = '[timeout:30][out:json];(node(around:%s,%s,%s);way(around:%s,%s,%s));out tags geom;relation(around:%s,%s,%s);' % (dist, yy, xx, dist, yy, xx, dist, yy, xx) reply1 = qnam.post(request, QByteArray(request_data)) loop = QEventLoop() reply1.finished.connect(loop.quit) loop.exec_() if reply1.error() != QNetworkReply.NoError: reply1.deleteLater() self.gotError.emit(self.tr('Error getting data from the server')) return try: data = reply1.readAll() l1 = json.loads(str(data))['elements'] reply1.deleteLater() except: self.gotError.emit(self.tr('Error parsing data')) return finally: reply1.deleteLater() request_data = '[timeout:30][out:json];is_in(%s,%s)->.a;way(pivot.a);out tags geom;relation(pivot.a);out tags bb;' % (yy, xx) reply2 = qnam.post(request, QByteArray(request_data)) loop = QEventLoop() reply2.finished.connect(loop.quit) loop.exec_() if reply2.error() != QNetworkReply.NoError: reply2.deleteLater() self.gotError.emit(self.tr('Error getting data from the server')) return try: data = reply2.readAll() l2 = json.loads(str(data))['elements'] except: self.gotError.emit(self.tr('Error parsing data')) return finally: reply2.deleteLater() self.gotData.emit(l1, l2)
class ActivityProtocol(QObject): # SIGNAL that is emitted after activities have been read readSignal = pyqtSignal(bool, int, str) # SIGNAL that is emitted after a new activity has been added created = pyqtSignal(bool, int, str) # SIGNAL that is emitted after an existing activity has been updated updated = pyqtSignal(bool, int, str) # SIGNAL that is emitted after an activity has been deleted deleted = pyqtSignal(bool, int, str) # SIGNAL that is emitted after activities have been counted counted = pyqtSignal(bool, int, str) finished = pyqtSignal( QNetworkReply ) def __init__(self, host, user, password): QObject.__init__(self) # Set the host self.host = host # Create a base64 encoded credential string from user name and password. # This is required for the HTTP basic access authentication, compare # also http://en.wikipedia.org/wiki/Basic_access_authentication self.userlogin = "******" % (user, password) self.login = "******" + QByteArray(self.userlogin).toBase64() # Create a new QNetworkAccessManager and connect it to the # authenticationRequired signal self.manager = QNetworkAccessManager(self) #self.connect(self.manager, SIGNAL("authenticationRequired( QNetworkReply*, QAuthenticator* )"), self.slotAuthenticationRequired) def update(self, rawBody): """ Update an activity using a POST request """ self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.updateRequestFinished) url = "%s/activities" % self.host qurl = QUrl(url) self.request = QNetworkRequest(qurl) self.request.setRawHeader("Authorization", self.login) self.request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.post(self.request, json.dumps(rawBody).decode("UTF-8")) return url def updateRequestFinished(self, reply): self.disconnect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.updateRequestFinished) # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)) #httpReasonPhrase = reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute) data = reply.readAll() self.updated.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, str(data)) def read(self, extent, iface): self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished) #self.finished.connect(self.readRequestFinished) # Get the map extent xmin = extent.xMinimum() ymin = extent.yMinimum() xmax = extent.xMaximum() ymax = extent.yMaximum() # Get the authority identifier for the projects destination reference # system. Normally in case of EPSG that authid looks like "EPSG:4326" authid = iface.mapCanvas().mapRenderer().destinationCrs().authid() authcode = int(authid.split(":")[-1]) # Add explicitly the EPSG code to the bounding box, to enable users to # work in a local reference system url = "%s/activities/json?bbox=%f,%f,%f,%f&epsg=%1.f" % (self.host, xmin, ymin, xmax, ymax, authcode) qUrl = QUrl(url) self.request = QNetworkRequest(qUrl) self.request.setRawHeader("Authorization", self.login) self.request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.get(self.request) return url def readRequestFinished(self, reply): # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)) #data = str("a") data = reply.readAll() # Check the status code see also http://en.wikipedia.org/wiki/HTTP_status_code # In case of a successful upload we get a 201 status code back and the # "stylePosted" signal is emitted with the first parameter set to True. # If the query didn't succeed, the status code is 4xx indicating that # the host was not found, the authentication failed or a forbidden # action in case a style with the same name already exists. It's up to # the receiver to handle these status codes. self.readSignal.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, str(data)) def readById(self, id): """ """ self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readByIdRequestFinished) # Get the latest version of the activity with this id url = "%s/activities/json/%s?geometry=full" % (self.host, id) qUrl = QUrl(url) self.request = QNetworkRequest(qUrl) self.request.setRawHeader("Authorization", self.login) self.manager.get(self.request) return url def readByIdRequestFinished(self, reply): # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute)) data = reply.readAll() self.readSignal.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, str(data))
def run(self): xx = str(self.__xx) yy = str(self.__yy) if abs(float(xx)) > 180 or abs(float(yy)) > 90: QgsMessageLog.logMessage( self.tr('Worker: %s, %s are wrong coords!') % (xx, yy), self.tr('OSMInfo'), QgsMessageLog.INFO ) self.gotError.emit(self.tr('Worker: %s, %s are wrong coords!') % (xx, yy)) return url = 'http://overpass-api.de/api/interpreter' request = QNetworkRequest(QUrl(url)) request.setHeader(QNetworkRequest.ContentTypeHeader, 'application/x-www-form-urlencoded'); qnam = QgsNetworkAccessManager.instance() # around request dist = PluginSettings.distance_value() timeout = PluginSettings.timeout_value() request_data = '[timeout:%s][out:json];(node(around:%s,%s,%s);way(around:%s,%s,%s);relation(around:%s,%s,%s););out tags geom;' % (timeout, dist, yy, xx, dist, yy, xx, dist, yy, xx) reply1 = qnam.post(request, QByteArray(request_data)) loop = QEventLoop() reply1.finished.connect(loop.quit) loop.exec_() if reply1.error() != QNetworkReply.NoError: reply1.deleteLater() self.gotError.emit(self.tr('Error getting data from the server')) return try: data = reply1.readAll() l1 = json.loads(str(data))['elements'] reply1.deleteLater() except: self.gotError.emit(self.tr('Error parsing data')) return finally: reply1.deleteLater() request_data = '[timeout:%s][out:json];is_in(%s,%s)->.a;way(pivot.a);out tags geom;relation(pivot.a);out geom;' % (timeout, yy, xx) reply2 = qnam.post(request, QByteArray(request_data)) loop = QEventLoop() reply2.finished.connect(loop.quit) loop.exec_() if reply2.error() != QNetworkReply.NoError: reply2.deleteLater() self.gotError.emit(self.tr('Error getting data from the server')) return try: data = reply2.readAll() l2 = json.loads(str(data))['elements'] except: self.gotError.emit(self.tr('Error parsing data')) return finally: reply2.deleteLater() self.gotData.emit(l1, l2)
class ActivityProtocol(QObject): # SIGNAL that is emitted after activities have been read readSignal = pyqtSignal(bool, int, QString) # SIGNAL that is emitted after a new activity has been added created = pyqtSignal(bool, int, QString) # SIGNAL that is emitted after an existing activity has been updated updated = pyqtSignal(bool, int, QString) # SIGNAL that is emitted after an activity has been deleted deleted = pyqtSignal(bool, int, QString) # SIGNAL that is emitted after activities have been counted counted = pyqtSignal(bool, int, QString) def __init__(self, host, user, password): QObject.__init__(self) # Set the host self.host = host # Create a base64 encoded credential string from user name and password. # This is required for the HTTP basic access authentication, compare # also http://en.wikipedia.org/wiki/Basic_access_authentication self.userlogin = "******" % (user, password) self.login = "******" + QByteArray(self.userlogin).toBase64() # Create a new QNetworkAccessManager and connect it to the # authenticationRequired signal self.manager = QNetworkAccessManager(self) # self.connect(self.manager, SIGNAL("authenticationRequired( QNetworkReply*, QAuthenticator* )"), self.slotAuthenticationRequired) def update(self, rawBody): """ Update an activity using a POST request """ self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.updateRequestFinished) url = "%s/activities" % self.host qurl = QUrl(url) self.request = QNetworkRequest(qurl) self.request.setRawHeader("Authorization", self.login) self.request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.post(self.request, QString(json.dumps(rawBody)).toUtf8()) return url def updateRequestFinished(self, reply): self.disconnect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.updateRequestFinished) # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute).toString()) # httpReasonPhrase = reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute).toString() data = reply.readAll() self.updated.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, QString(data)) def read(self, extent): self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readRequestFinished) # Limit the longitude and latitutde maximum boundaries xmin = extent.xMinimum() if extent.xMinimum() >= -180 else -180 ymin = extent.yMinimum() if extent.yMinimum() >= -90 else -90 xmax = extent.xMaximum() if extent.xMaximum() <= 180 else 180 ymax = extent.yMaximum() if extent.yMaximum() <= 90 else 90 url = "%s/activities/json?bbox=%d,%d,%d,%d" % (self.host, xmin, ymin, xmax, ymax) qUrl = QUrl(url) self.request = QNetworkRequest(qUrl) self.request.setRawHeader("Authorization", self.login) self.request.setHeader(QNetworkRequest.ContentTypeHeader, "application/json") self.manager.get(self.request) return url def readRequestFinished(self, reply): # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute).toString()) # data = str("a") data = reply.readAll() # Check the status code see also http://en.wikipedia.org/wiki/HTTP_status_code # In case of a successful upload we get a 201 status code back and the # "stylePosted" signal is emitted with the first parameter set to True. # If the query didn't succeed, the status code is 4xx indicating that # the host was not found, the authentication failed or a forbidden # action in case a style with the same name already exists. It's up to # the receiver to handle these status codes. self.readSignal.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, QString(data)) def readById(self, id): """ """ self.connect(self.manager, SIGNAL("finished( QNetworkReply* )"), self.readByIdRequestFinished) # Get the latest version of the activity with this id url = "%s/activities/json/%s?geometry=full" % (self.host, id) qUrl = QUrl(url) self.request = QNetworkRequest(qUrl) # self.request.setRawHeader("Authorization", self.login) self.manager.get(self.request) return url def readByIdRequestFinished(self, reply): # Get the HTTP status code from the reply self.httpStatusCode = int(reply.attribute(QNetworkRequest.HttpStatusCodeAttribute).toString()) data = reply.readAll() self.readSignal.emit(self.httpStatusCode in (200, 201), self.httpStatusCode, QString(data))
def get_data(self): request = QNetworkRequest(QUrl(self.config.url)) request.setHeader(QNetworkRequest.ContentTypeHeader, 'text/xml') # or? "text/xml; charset=utf-8" reply = self.network_manager.post(request, self.xml()) filename = self.config.output_dir + '/modelinfo.json' reply.finished.connect(partial(self._data_retrieved, reply, filename))