簡體   English   中英

插入pymongo集合時,“ str”對象不支持項目分配

[英]'str' object does not support item assignment when inserting to pymongo collection

RHEL 6.5,Python 2.6.6

我正在嘗試將解碼后的消息寫入MongoDB集合中。 以字典的形式接收“解碼的消息”。 在該字典中,鍵是所有字符串,值可以是字符串,整數, datetime.timedatetime.datetimeDecimal類型。

我編寫了一個on_message函數,該函數使用參數context調用,以繼續將字典保存到MongoDB。 我還編寫了一個lambda來轉換一些無法JSON序列化的類型。

dthandler = lambda obj: (
    str(obj) 
    if isinstance(obj, Decimal)
    or isinstance(obj, datetime.time)
    else None
)

class Decoder(decoder.base.Base):

  # ...

  def on_message(self, context, payload):

    """  Write decoded message to DB
    """
    msg = dict(context)
    try:

        print self.mongo_coll

        # This is just a test to confirm the connection is established properly.
        # I am able to see this value in the DB using Robomongo after this insert 
        # call
        self.mongo_coll.insert({'foo': 'john'})

        x = json.dumps(context, default=dthandler)
        print x
        self.mongo_coll.insert(x)
    except errors.OperationFailure as op:
        print "Operation Exception"

    except Exception as ex:
        print "Serialization Exception (mongo/write.py)"
        exs = str(ex)
        print exs

        print '^^^^^'

調用print self.mongo_coll產生:

集合(數據庫(MongoClient('localhost',27017),u'itch'),u'test')

調用print x產生收益(所有結果都是相似的):

{“ msg-type-name”:“ AddOrderAttributed”,“ next-expect-msg-seq-num”:3023982,“ mold-num-msgs”:34,“ recv-timestamp”:null,“ ord-ref- num”:4365786,“ msg-type”:“ F”,“ recv-time-nano”:2523000,“ raw-price”:781200,“ msg-seq-num”:3023981,“ shares”:100,“ “買賣”:“ B”,“股票”:“ RNR”,“屬性”:“ RBCM”,“時間戳”:“ 09:30:00.002189”,“價格”:“ 78.12”,“跟蹤號” :1,1,“ recv-time-sec”:1419431400,“ msg-size”:40,“ mold-seq-num”:3023959,“ stock-locate”:6281,“ mold-session”:“ 000006896B”,“ msg-payload“:““ 00 28 46 18 89 00 01 1f 1a ce fb 57 59 00 00 00 00 00 00 42 9d da 42 00 00 00 64 52 4e 52 20 20 20 20 20 00 0b eb 90 52 42”}

但是,對self.mongo_coll.insert(x)的調用會產生Exception

序列化異常(mongo / write.py)

'str'對象不支持項目分配

^^^^^

我非常困惑,特別是考慮到我的代碼中沒有提到str ,除了我的異常處理程序和dthandler

我究竟做錯了什么?


根據編輯和答案,我做了一些修改。 ,我仍然有麻煩。 這是新的代碼:

 def on_message(self, context, payload):
    """  Write decoded message to DB
    """
    msg = dict(context)
    try:
        print self.mongo_coll
        self.mongo_coll.insert(msg)
        x = json.dumps(context, default=dthandler)
        print self.mongo_coll
        print x
        self.mongo_coll.insert(msg)
    except errors.OperationFailure as op:
        print "Operation Exception"
    except Exception as ex:
        traceback.print_exc()
        print "Serialization Exception (mongo/write.py)"
        exs = str(ex)
        print exs

        print '^^^^^'

...以及輸出:

Collection(Database(MongoClient('localhost', 27017), u'itch'), u'test')
Traceback (most recent call last):
  File "./decoder/mongo/write.py", line 69, in on_message
    self.mongo_coll.insert(msg)
  File "/usr/lib64/python2.6/site-packages/pymongo/collection.py", line 409, in insert
    gen(), check_keys, self.uuid_subtype, client)
InvalidDocument: Cannot encode object: Decimal('65.1')
Serialization Exception (mongo/write.py)
Cannot encode object: Decimal('65.1')
^^^^^

你的線在這里

x = json.dumps(context, default=dthandler)

使x為字符串。 只需使用

self.mongo_coll.insert(msg)

最好不要直接插入context ,而應插入msg (這是dict ,而不是上下文對象)。

我不知道這是否解決。 但是我遇到了同樣的問題,因此我將在此處發布我的解決方案以幫助他人。

我正在研究這個例子

問題代碼:

# insert the student object into MongoDB
object_id = student_collection.insert(a_student.to_JSON())

解:

object_id = student_collection.insert({"email": "daniel@mongocourse.com", "name": {"first": "Daniel", "last": "Watrous"}, "major": "Electrical Engineering"})

即使我們在這里說“ to_JSON()”,insert方法也會感到困惑,並且在執行時會拋出錯誤。 因為它得到一個字符串,所以認為它是一個字符串,而不是JSON。

我正在使用Python 3.5。 該版本也可能與此有關。 也許它適用於Python 2.7。

希望這會幫助某人。

我遇到了與您相同的問題,並且找到了以下解決方案:

import json    

valuestr = json.dumps(myclass, default=lambda x:x.__dict__)
value = json.loads(valuestr) # <-- returned data is not string
db.posts.insert(value)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM