def loadStamps(self): prefs = preferences.Preferences.instance() stampsDirectory = prefs.stampsDirectory() stampsDir = QDir(stampsDirectory) iterator = QDirIterator(stampsDirectory, ["*.stamp"], QDir.Files | QDir.Readable) while (iterator.hasNext()): stampFileName = iterator.next() stampFile = QFile(stampFileName) if (not stampFile.open(QIODevice.ReadOnly)): continue data = stampFile.readAll() document = QJsonDocument.fromBinaryData(data) if (document.isNull()): # document not valid binary data, maybe it's an JSON text file error = QJsonParseError() document = QJsonDocument.fromJson(data, error) if (error.error != QJsonParseError.NoError): qDebug("Failed to parse stamp file:" + error.errorString()) continue stamp = TileStamp.fromJson(document.object(), stampsDir) if (stamp.isEmpty()): continue stamp.setFileName(iterator.fileInfo().fileName()) self.mTileStampModel.addStamp(stamp) index = stamp.quickStampIndex() if (index >= 0 and index < self.mQuickStamps.size()): self.mQuickStamps[index] = stamp
def notify(self, json_obj): json_doc = QJsonDocument(json_obj) data = json_doc.toJson(QJsonDocument.Compact) self.logger.info("Notifing %s with %s...", self.url, data) req = QNetworkRequest(QUrl(self.url)) req.setHeader(QNetworkRequest.ContentTypeHeader, 'application/json') self.networkAccessManager.post(req, data)
def _finished_getting_reply(self, reply): error = reply.error() if error == QNetworkReply.NoError: bytes_string = reply.readAll() document = QJsonDocument().fromJson(bytes_string) args = self.addicional_args.pop(len(self.addicional_args) - 1) if not document.isNull(): self.redirect_fun(document, args) self._busy = False else: print("error") else: print("Error occured: ", error) print(reply.errorString())
def textMessageReceived(self, messageData): error = QJsonParseError() message = QJsonDocument(eval(messageData)) ''' if error: print("Failed to parse text message as JSON object:", messageData) print("Error is:", error.errorString()) return elif not messageData.isObject(): print("Received JSON message that is not an object: ", messageData) return ''' self.messageReceived.emit(message.object(), self)
def post(self, url: str, jsonBody: dict, param: dict = None): path = QUrl(url) sendData = QJsonDocument(jsonBody) if param != None: queryParams = QUrlQuery() for item in param.items(): queryParams.addQueryItem(item[0], str(item[1])) path.setQuery(queryParams.query()) req = QtNetwork.QNetworkRequest(path) # 设置头信息是json这里可以不写 # req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/json") self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) self.nam.post(req, sendData.toJson())
def doLogin(self): jsonbody = {"username": "******", "password": "******"} sendData = QJsonDocument(jsonbody) print(sendData.toJson()) url = "http://localhost:18080/user/login" # dic = QByteArray() # dic.append("username=admin&") # dic.append("password=111111") req = QtNetwork.QNetworkRequest(QUrl(url)) # req.setHeader(QtNetwork.QNetworkRequest.ContentTypeHeader, "application/json") self.nam = QtNetwork.QNetworkAccessManager() self.nam.finished.connect(self.handleResponse) # 使用get请求 如果有参数的话 写一个data 放到get里 self.nam.post(req, sendData.toJson())
def loadJsonFromByteArray(self, byteArray: QByteArray): json = QJsonDocument(QJsonDocument.fromJson(byteArray)) topLevelObject = json.object() nodeStyleValues = topLevelObject["FlowViewStyle"] obj = nodeStyleValues.toObject() self.BackgroundColor = self.flowViewStyleReadColor( obj, "BackgroundColor") self.FineGridColor = self.flowViewStyleReadColor(obj, "FineGridColor") self.CoarseGridColor = self.flowViewStyleReadColor( obj, "CoarseGridColor")
def uninit(self): json = {} json["HighestScore"] = self.highestScore #写入最高分 json["HighestScorePlayer"] = self.highestScorePlayer #写入最高分保持者 json["ThemePath"] = self.themePath #写入主题文件路径 jsonDocument = QJsonDocument() jsonDocument.setObject(json) b = jsonDocument.toJson() #写入json f = QFile("config.ini") f.open(QFile.WriteOnly | QFile.Truncate) f.write(b) f.close()
def init(self): #初始化设置默认值 self.highestScore = 0 #最高分 self.highestScorePlayer = "" #最高分保持者 self.themePath = "theme\\default.qss" #主题路径 f = QFile("config.ini") #如果设置文件存在则从中读入设置数据 if f.exists(): #读取文件 f.open(QFile.ReadOnly) b = f.readAll() f.close() #解析json jsonDocument = QJsonDocument.fromJson(b) json = jsonDocument.object() self.highestScore = json["HighestScore"].toInt() #读取最高分 self.highestScorePlayer = json["HighestScorePlayer"].toString( ) #读取最高分保持者 self.themePath = json["ThemePath"].toString() #读取当前主题文件路径 #否则创建设置文件并用默认设置进行游戏 else: f.open(QFile.WriteOnly) f.close() #设置主题 self.setTheme(self.themePath)
def slotDataReceived(self): recvData = b'' client_sock = self.sender() client = self.client_list[self.findClient(client_sock)] while client_sock.bytesAvailable() > 0: recvData += client_sock.read(client_sock.bytesAvailable()) recvData = QJsonDocument().fromJson(recvData) self.parseData(client, recvData)
def toJson(self): j = QJsonDocument().object() j["type"] = self.getType2String() j["state"] = self.getState2String() j["url"] = self.url j["filename"] = self.fileName j["curProgress"] = self.curProgress j["totalFile"] = self.totalFile j["finishFile"] = self.finishFile j["fileSize"] = self._total return j
def init_widget(self): self.setWindowTitle("QWebChannel") self.setFixedWidth(640) self.setFixedHeight(480) # 로컬파일 사용시 절대경로만 사용해야 함 url = QDir().current().filePath( "html/QWebEngineView_09_WebChannelDataType.html") url = QUrl.fromLocalFile(url) self.web.load(url) # 핸들러 시그널 버튼이 눌러지면 console로 value를 보낸다. value = {"data": "ABC", "msg": ["DEF", 1, {"A": False, "B": True}]} document = QJsonDocument() document.setObject(value) self.pb_1.clicked.connect( lambda v: self.handler.app_to_web_send_data.emit(document)) self.layout_2.addWidget(self.web) self.layout_3.addWidget(self.pb_1)
def sendStatus(self): sendData = {'type': TYPE_RESPONSE_STATUS, 'roomId': self.roomId, 'mode': self.mode, 'roomTemp': self.roomTemp, 'setTemp': self.setTemp, 'windSpeed': self.windSpeed, 'energy': self.energy, 'money': self.money} sendData = QJsonDocument(sendData).toJson() self.sock.write(sendData)
def textMessageReceived(self, message): print('textMessageReceived:', message) error = QJsonParseError() json = QJsonDocument.fromJson(message.encode('utf-8', errors='ignore'), error) if error.error: print('Failed to parse message:{}, Error is:{}'.format( message, error.errorString())) return if not json.isObject(): print('Received JSON message that is not an object:{}'.format( message)) return self.messageReceived.emit(json.object(), self)
def loadJsonFromConsole(self, value): error = QJsonParseError() self.mDocument = QJsonDocument.fromJson(value, error) if self.mDocument is not None: self.beginResetModel() if self.mDocument.isArray(): self.mRootItem.load(list(self.mDocument.array())) else: self.mRootItem = self.mRootItem.load(self.mDocument.object()) self.endResetModel() return True print("QJsonModel: error loading Json") return False
def saveStamp(self, stamp): # make sure we have a stamps directory prefs = preferences.Preferences.instance() stampsDirectory = prefs.stampsDirectory() stampsDir = QDir(stampsDirectory) if (not stampsDir.exists() and not stampsDir.mkpath(".")): qDebug("Failed to create stamps directory" + stampsDirectory) return filePath = stampsDir.filePath(stamp.fileName()) file = QSaveFile(filePath) if (not file.open(QIODevice.WriteOnly)): qDebug("Failed to open stamp file for writing" + filePath) return stampJson = stamp.toJson(QFileInfo(filePath).dir()) file.write(QJsonDocument(stampJson).toJson(QJsonDocument.Compact)) if (not file.commit()): qDebug() << "Failed to write stamp" << filePath
def textMessageReceived(self, messageData): error = QJsonParseError() message = QJsonDocument.fromJson(bytes(messageData)) if error.error: qWarning("Error parsing text message '%s' to JSON object: %s" % (messageData, error.errorString())) return elif not message.isObject(): qWarning("Received JSON message that is not an object: %s", messageData) return print("message:", message, "object:", message.object(), "type: ", type(message.object()), file=sys.stderr) self.messageReceived.emit(message.object(), self)
def send_notification(self, text): _klass = 'org/kviktor/example/ExampleActivity' try: from PyQt5.QtAndroidExtras import QAndroidJniObject logger.info('QtAndroidExtras/QAndroidJniObject import successful') logger.info(f'QAndroidJniObject.isClassAvailable({_klass}): ' f'{QAndroidJniObject.isClassAvailable(_klass)}') json_doc = QJsonDocument({ 'text': text, 'title': 'sent from Python', }) retval = QAndroidJniObject.callStaticMethod( _klass, 'sendNotification', json_doc) logger.info('sendNotification call done, retval: %s', retval.object()) except ImportError: logger.exception('Could not import QtAndroidExtras')
def SearchPTH(queryString, language): request = QNetworkRequest() request.setUrl(QUrl("https://paikkatietojentuottajat-koekaytto.maanmittauslaitos.fi/api/public/v1/search?X-CLIENT-LANG=FI")) request.setHeader(request.ContentTypeHeader, "application/json") jsonByteArray = QJsonDocument(createJson(queryString, language)).toJson() blockingNetworkRequest = QgsBlockingNetworkRequest() err = blockingNetworkRequest.post(request, jsonByteArray, True) if not err: response = blockingNetworkRequest.reply().content() dict_str = response.data().decode("utf-8") if dict_str: resp_json = json.loads(dict_str) return resp_json.get("hits") else: #No result returned LOG("Nothing returned") pass else: LOG(blockingNetworkRequest.errorMessage())
# 로컬파일 사용시 절대경로만 사용해야 함 #url = QDir().current().filePath("html/QWebEngineView_02_WebChannel.html") url = os.path.join(settings.BASE_DIR, 'Lumos_UI', 't-map', 'index.html') url = QUrl.fromLocalFile(url) self.web.load(url) # 핸들러 시그널 버튼이 눌러지면 console로 Hi를 보낸다. self.pb_1.clicked.connect( lambda v: self.handler.getText.emit(txt)) ##경로얻어오기 self.pb_2.clicked.connect( lambda v: self.web.setUrl(QUrl("http://google.com"))) ##밝기지도 self.pb_3.clicked.connect( lambda v: self.web.setUrl(QUrl(url))) ##길찾기 API self.layout_2.addWidget(self.web) # self.layout_3.addWidget(self.pb_1) # self.layout_3.addWidget(self.pb_2) # self.layout_3.addWidget(self.pb_3) #self.layout_3.addWidget(self.te_1) txt = '' if __name__ == "__main__": sys.argv.append("--remote-debugging-port=8000") app = QApplication(sys.argv) document = QJsonDocument() form = Form() form.show() exit(app.exec_())
from TreeModel import TreeModel from reader import read_js if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) # f = QtCore.QFile('default.txt') # f.open(QtCore.QIODevice.ReadOnly) # model = TreeModel(f.readAll()) # f.close() parse_err = QJsonParseError() byte_array = read_js('../example.json') json_document = QJsonDocument.fromJson(byte_array, parse_err) if QJsonParseError.NoError == parse_err.error: print(parse_err.errorString()) # json_document = QJsonDocument() model = TreeModel(json_document) view = QtWidgets.QTreeView() view.setModel(model) view.setWindowTitle("Json Tree Model") view.show() sys.exit(app.exec_())
def sendMessage(self, message): doc = QJsonDocument(message) self._socket.sendTextMessage(doc.toJson(QJsonDocument.Compact))
st = ' {\n' json_document_object = None if isinstance(json_document, QJsonDocument): json_document_object = json_document.object() elif isinstance(json_document, QJsonValue): json_document_object = json_document.toObject() for obj in json_document_object: st += obj + ': ' + get_type(json_document_object[obj]) + '\n' st = st[:-1] st += '\n}' return st return '' if __name__ == '__main__': parse_err = QJsonParseError() byte_array = read_js('example.json') json_document = QJsonDocument.fromJson(byte_array, parse_err) if QJsonParseError.NoError == parse_err.error: print(parse_err.errorString()) # if json_document.isObject(): # json_object = json_document.object() # for k in json_object: # print(k + ': ' + str(json_object[k].toVariant())) print(get_type(json_document))
def sendMessage(self, message): print('sendMessage:', message) self.m_socket.sendTextMessage( QJsonDocument(message).toJson(QJsonDocument.Compact).data().decode( 'utf-8', errors='ignore'))
def test_set_json_object(): json_object = QJsonDocument() model = QJsonTreeModel(json_object) assert model.jsonDocument().isEmpty()
def weather_data_received(self): json_str = self._current_weather.readAll() json_doc = QJsonDocument.fromJson(json_str) self._read_current_weather_data(json_doc.object())
def forecast_data_received(self): json_str = self._forecast_weather.readAll() json_doc = QJsonDocument.fromJson(json_str) self._read_forecast_data(json_doc.object())
def sendMessage(self, message): doc = QJsonDocument(message) self.m_socket.sendTextMessage(doc.toJson().data().decode('utf-8'))
def slotRequestStatus(self): sendData = QJsonDocument({'type': TYPE_REQUEST_STATUS}).toJson() for client in self.client_list: client.sock.write(sendData)
def slotDataReceived(self): recvData = b'' while self.sock.bytesAvailable() > 0: recvData += self.sock.read(self.sock.bytesAvailable()) recvData = QJsonDocument().fromJson(recvData) self.parseData(recvData)