Python 在pymongo中读取线程时未获得任何结果
我试图在mongodb中保存条目并获取id。然后我想在线程中找到该条目。但有时我做不到Python 在pymongo中读取线程时未获得任何结果,python,mongodb,pymongo,Python,Mongodb,Pymongo,我试图在mongodb中保存条目并获取id。然后我想在线程中找到该条目。但有时我做不到 import pymongo import bson import threading connection = pymongo.Connection("localhost", 27017) db = connection.test def set_cache(db): cache_id = db.test_collection.save({'test': 'some string'})
import pymongo
import bson
import threading
connection = pymongo.Connection("localhost", 27017)
db = connection.test
def set_cache(db):
cache_id = db.test_collection.save({'test': 'some string'})
return cache_id
def get_cache(db, cache_id):
entry = db.test_collection.find_one({'_id' : bson.objectid.ObjectId(cache_id)})
if not entry:
print('No entry for %s' % cache_id)
return entry
i = 0
while 1:
i += 1
cache_id = set_cache(db)
t = threading.Thread(target=get_cache, args=(db, cache_id))
t.start()
t.join()
if i > 10000:
break
所以,有时我看到“没有……的条目”。但我可以在mongo看到这个条目。
蟒蛇2.6
mongo 2.0.6您的实现的问题是,您使用的是未确认的写入,默认用法是
pymongo.Connection
。通过使用此选项,您可以进入这样的情况:写入未在内存中确认,但在客户端收到确认。如果您更快地处理响应并发出find请求,您将遇到类似这样的情况。你基本上太快了:)
现在,如果您使用w:1确认,或者仅使用新的pymongo.MongoClient
类(我鼓励您这样做),您将不会遇到这种情况:
import pymongo
import bson
import threading
connection = pymongo.MongoClient("localhost", 27017)
db = connection.test
def set_cache(db):
cache_id = db.test_collection.save({'test': 'some string'})
return cache_id
def get_cache(db, cache_id):
entry = db.test_collection.find_one({'_id' : bson.objectid.ObjectId(cache_id)})
if not entry:
print('No entry for %s' % cache_id)
return entry
i = 0
while 1:
i += 1
cache_id = set_cache(db)
t = threading.Thread(target=get_cache, args=(db, cache_id))
t.start()
t.join()
if i > 10000:
break
N.我发现了一个问题。使用保存选项w=1