QJsonDocument /(QJsonObject)上的PyQt5丢失方法

时间:2018-02-14 11:38:20

标签: python pyqt pyqt5

我正在尝试通过REST API端口使用PyQt5连接到扫描仪。 Scanner / API使用Json Documents进行连接和身份验证。但是我在创建PyQt5 Json文档时遇到问题,该文档包含与示例C ++代码相同的信息。

PyQt5参考指南告诉我,QJsonObject是作为str键和QJsonValue值的" dict实现的。 QJsonObject PyQt5 reference guide。当我尝试将它们插入到QJsonObject中时,它没有被插入,因为QJsonObject没有" setObject" PyQt5中的方法。

如何确保将相同的消息发送到服务器,就像在C ++中一样? 这有解决方法吗?

我在C ++中有这个示例代码我试图用python代码替换(下面):

QWebSocket socket;
QString address = …;
QString port = …;
connect(&socket,&QWebSocket::textMessageReceived,this,&Client::onTextMessageReceived);
socket.open(QUrl(QString("ws://%1:%2").arg(address).arg(port)));

void onTextMessageReceived(QString aMessage)
    {
    QJsonDocument doc = QJsonDocument::fromJson(aMessage.toUtf8());
    QJsonObject o = doc.object();
    if(o.contains("event")){
        QString type = o.value("event").toString();

        if(type == "authenticate"){
            QByteArray challenge = QByteArray::fromBase64( o.value("challenge").toString().toUtf8() );
            QString signature = \\signature here
            QJsonDocument d;
            QJsonObject response;
            response.insert("event", "authenticate");
            response.insert("response",signature);
            d.setObject(response);
           socket.sendTextMessage(d.toJson());
        }
        else if(type == "authenticated"){
            token = doc.object().value("token").toString();
        }
}

Python代码:

    self.client.textMessageReceived.connect(self.onTextmsgReceived)
    # connect websocket to port
    self.client.open(QUrl("ws://"+UDP_IP+":"+str(notificationsport)))


def onTextmsgReceived(self, message):
    # this method is to receive the challenge message from the scanner
    # it signs the challenge and authenicates with the agent/scanner
    print(type(message))
    print(message)
    if "event\": \"authenticate" in message:
        if "authenticated" in message:
            print("Autheticated!")

        json_challange = json.loads(message)
        challenge_str = json_challange["challenge"]
        signature = signmsg(challenge_str,priv_key)# sign challenge
        #signature_dict = {"response":QtCore.QJsonValue(signature.decode('utf8')),"event":QtCore.QJsonValue("authenticate")} # doesn't work - working with normal strings:
        signature_dict = {"response":signature.decode('utf8'),"event":"authenticate"}


        d = QtCore.QJsonDocument(signature_dict) # trying to inset dict directly        
        #d.setObject(signature_dict) # not working
        document = d.toJson()
        #self.client.sendTextMessage(document) # does not work  trying with str()
        self.client.sendTextMessage(str(document))
        print("Ready")



    elif "authenticated" in message:
        print("Autheticated!")
        #token = 

0 个答案:

没有答案