TypeError:使用python将字节存储到mongo db时

时间:2018-08-11 16:59:44

标签: python multithreading mongodb

我正在尝试编写一个大型程序来与服务器进行客户端通信,并且一切正常,但是当我尝试将客户端数据存储到在服务器端连接的Mongodb时,出现以下错误。

错误:

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, or a type that inherits from collections.MutableMapping

在客户端,我的数据类型显示为字符串,而在服务器端,当我打印表示其字节的类型时,数据类型显示为字符串。但是为什么字节不存储在数据库中。请发表您的想法,我也是python的新手。 谢谢

ServerSide:

import re
#getting ip address from machine and bd it to the client
class C():



          if __name__ == "__main__":
              ethernet_card = "wlp3s0"
              ip = ip1(ethernet_card)
          self.sock.bind((ip,4242))
          self.clients_list = []



    def talkToClient(self, ip):
            self.sock.sendto("ok".encode('utf-8'), ip)

    def listen_clients(self):
        #listen to multiple clients
            def parse(msg):
                uri = "mongodb://localhost:27017"
                client = pymongo.MongoClient(uri)
                database = client['orchtrail']
                collection = database['testData']
                result = database.testData.insert_many(msg)
                testData = collection.find({})
                for test in testData:
                    print(test)
                result.inserted_id
            while True:
                msg, client = self.sock.recvfrom(1024)
                print(type(msg))
                print(msg)
                parse(msg)

                print('connected with : ' + client[0]+ ':' + str(client[1]))
                t = threading.Thread(target= self.talkToClient,args=(client,))
                t.start()

if __name__=='__main__':
    C= C()
    C.broad(msg="")
    C.listen_clients()

客户端

temperature=""
hum=""
json=json.dumps({"temp"=temperature,"hum":hum})
msg=json
self.sock.sendto(msg.encode(),address)

1 个答案:

答案 0 :(得分:0)

您要在以下位置插入数据

result = database.testData.insert_many(msg)

该错误表明msg应该是dict,但是您写了您检查的内容,它的类型为byte

因此,您的问题是:如何将以json存储的bytes转换为dict

您可以执行以下操作:

import pickle
import json

msg_as_dict = json.loads(pickle.loads(msg))

# check the type of msg_as_dict
print(type(msg_as_dict)) # should be <class 'dict'>

然后保存到您的Mongo数据库:

result = database.testData.insert_many(msg_as_dict )