2013-01-03 80 views
2

有誰知道可以將類對象轉換爲mongodb BSON字符串的Python庫嗎?目前我唯一的解決方案是將類對象轉換爲JSON,然後將JSON轉換爲BSON。將Python類對象實例轉換爲mongodb BSON字符串

+1

您是否在尋找[pymonogo(http://api.mongodb.org/python/current/tutorial.html)可能? – WiredPrairie

+0

我不知道將python類對象轉換爲BSON的pymongo幫助器類嗎? –

+0

你想做什麼? [編碼](http://api.mongodb.org/python/current/api/bson/index.html?highlight=bson#bson.BSON.encode)轉換爲BSON。 – WiredPrairie

回答

1

將類實例轉換爲字典(如Python dictionary from an object's fields中所述),然後在生成的字典上使用bson.BSON.encode即可。請注意,__dict__的值不會包含方法,僅包含屬性。另請注意,可能會出現這種方法無法直接工作的情況。

如果您有需要存儲在MongoDB中的類,您可能還想考慮現有的ORM解決方案,而不是自己編寫代碼。這些列表可以在http://api.mongodb.org/python/current/tools.html

示例中找到:

>>> import bson 
>>> class Example(object): 
...  def __init__(self): 
...    self.a = 'a' 
...    self.b = 'b' 
...  def set_c(self, c): 
...    self.c = c 
... 
>>> e = Example() 
>>> e 
<__main__.Example object at 0x7f9448fa9150> 
>>> e.__dict__ 
{'a': 'a', 'b': 'b'} 
>>> e.set_c(123) 
>>> e.__dict__ 
{'a': 'a', 'c': 123, 'b': 'b'} 
>>> bson.BSON.encode(e.__dict__) 
'\x1e\x00\x00\x00\x02a\x00\x02\x00\x00\x00a\x00\x10c\x00{\x00\x00\x00\x02b\x00\x02\x00\x00\x00b\x00\x00' 
>>> bson.BSON.encode(e) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/local/lib/python2.7/dist-packages/bson/__init__.py", line 566, in encode 
    return cls(_dict_to_bson(document, check_keys, uuid_subtype)) 
TypeError: encoder expected a mapping type but got: <__main__.Example object at   0x7f9448fa9150> 
>>> 
+0

謝謝你的例子,我決定根據你的建議使用明。 –

+0

我開始在明的開發,但它是一個可怕的ORM,所以我們去了mongokit,很好地建立在pymongo之上 –