【问题标题】:MongoClient opened before fork. Create MongoClient onlyMongoClient 在 fork 之前打开。仅创建 MongoClient
【发布时间】:2019-09-20 07:32:32
【问题描述】:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["game"]
mycol = mydb["test_collection"]


class ProcessWork:
    res1 = []
    res2 = []

    def processwork1(request, res1):
        country = request.GET.get('country')
        qry = {'country': country}
        query = mycol.find(qry).limit(10)
        result = json.loads(dumps(query))
        res1.append(result)

    def processwork2(request, res2):
        country = request.GET.get('country')
        qry = {'country': country}
        query = mycol.find(qry).skip(10).limit(10)
        result = json.loads(dumps(query))
        res2.append(result)

    def process(request):
        t1 = multiprocessing.Process(target=ProcessWork.processwork1, args=((request), ProcessWork.res1))
        t2 = multiprocessing.Process(target=ProcessWork.processwork1, args=((request), ProcessWork.res2))

        t1.start()
        t1.join()
        t2.start()
        t2.join()
        # result = ProcessWork.res1[0] + ProcessWork.res2[0]
        return JsonResponse({})

终端错误:

    /home/fractaluser/Desktop/Dev/cache/env/lib/python3.5/site-packages/pymongo/topology.py:150: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#is-pymongo-fork-safe
      "MongoClient opened before fork. Create MongoClient only "
    /home/fractaluser/Desktop/Dev/cache/env/lib/python3.5/site-packages/pymongo/topology.py:150: UserWarning: MongoClient opened before fork. Create MongoClient only after forking. See PyMongo's documentation for details: http://api.mongodb.org/python/current/faq.html#is-pymongo-fork-safe
      "MongoClient opened before fork. Create MongoClient only "

我在这里使用多处理在 python 中运行多个任务。 我正在使用 pymongo 客户端从 mongodb 获取数据。

我无法理解这个错误。 由于这个结果,我也没有得到结果。

请看一下

【问题讨论】:

  • 我也遇到了同样的问题,希望您能与我们分享您的解决方案

标签: python mongodb multiprocessing


【解决方案1】:

您是否尝试过在 processwork2()processwork1() 方法中创建 Mongo 连接?

您在 fork() 系统调用发生之前创建 MongoClient(可能是操作系统创建新进程的一部分)。

只需将这部分放在方法体中即可:

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["game"]
mycol = mydb["test_collection"]

【讨论】:

    猜你喜欢
    • 2018-12-10
    • 2018-03-08
    • 2021-03-23
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2014-05-04
    • 2016-05-10
    相关资源
    最近更新 更多