我正在尝试将MongoDb Object id存储到yaml文件中,我还需要将其加载回来。但我目前正努力将其导出为yaml文件。我找到了一个例子,表明可以做到这一点。我想要遵循的示例是https://groups.google.com/forum/#!topic/mongodb-user/f0wDJAnCOS0
# My variable name
collection_insert_id
ObjectId('5923bb676cab3d37c45012a1')
# variable type
type(collection_insert_id)
<class 'bson.objectid.ObjectId'>
# this is a snip of the example I am following, Its throwing an error
def objectid_representer(dumper, data):
return dumper.represent_scalar("!bson.objectid.ObjectId", str(data))
yaml.SafeDumper.add_representer(collection_insert_id, objectid_representer)
yaml.safe_dump(my_dict, 'data.yaml',default_flow_style=False)
# This is the error I get when passing the second line.
File "<stdin>", line 1, in <module>
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-packages/yaml/__init__.py",
line 216, in safe_dump
return dump_all([data], stream, Dumper=SafeDumper, **kwds)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/__init__.py", line 188, in dump_all
dumper.represent(data)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 26, in represent
node = self.represent_data(data)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 47, in represent_data
node = self.yaml_representers[data_types[0]](self, data)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 203, in represent_dict
return self.represent_mapping('tag:yaml.org,2002:map', data)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 116, in represent_mapping
node_value = self.represent_data(item_value)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 57, in represent_data
node = self.yaml_representers[None](self, data)
File "/ws/mastarke-sjc/pyats2/lib/python3.4/site-
packages/yaml/representer.py", line 227, in represent_undefined
raise RepresenterError("cannot represent an object: %s" % data)
yaml.representer.RepresenterError: cannot represent an object:
5923bb676cab3d37c45012a1
# This is the code I am trying to follow that suggest how to send MongoDB
# object id to yaml file
def objectid_representer(dumper, data):
return dumper.represent_scalar("!bson.objectid.ObjectId", str(data))
yaml.SafeDumper.add_representer(objectid.ObjectId, objectid_representer)
yaml.safe_dump(doc_with_objectid, yamlfile, default_flow_style=False)