多进程中使用PyMongo

在Unix系统上,多进程模块使用fork()生成进程。但MongoClient的实例不能从父进程复制到子进程,父进程和每个子进程必须创建他们自己的MongoClient实例。

'''mongo.py'''
def dbconnect():
    client = MongoClient(host='192.168.199.7', port=27017, connect=False)
    client['test'].authenticate('root', 'sa', mechanism='SCRAM-SHA-1')
    return client['test']

'''main.py'''
from .mongo import dbconnect
......
proc = multiprocessing.Process(target=dbconnect)
proc.start()

错误使用:

'''mongo.py'''
client = MongoClient(host='192.168.199.7', port=27017, connect=False)
client['test'].authenticate('root', 'sa', mechanism='SCRAM-SHA-1')
def dbconnect():
    return client['test']

 

posted @ 2018-11-07 15:57  yudis  阅读(745)  评论(0编辑  收藏  举报