[英]TypeError: 'str' object does not support item assignment with PyMongo (MongoDB API)
[英]'str' object does not support item assignment when inserting to pymongo collection
RHEL 6.5,Python 2.6.6
我正在尝试将解码后的消息写入MongoDB集合中。 以字典的形式接收“解码的消息”。 在该字典中,键是所有字符串,值可以是字符串,整数, datetime.time
, datetime.datetime
或Decimal
类型。
我编写了一个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.