【问题标题】:How to use multiple functions in twisted deferToThread?如何在扭曲的 deferToThread 中使用多个函数?
【发布时间】:2016-12-02 13:57:25
【问题描述】:

根据有关 twisted deferToThread (http://twistedmatrix.com/documents/current/api/twisted.internet.threads.deferToThread.html) 的文档,我可以给它一个函数和参数。

我想限制我将找到的文档的输出(比如 3 个文档),所以我还想使用 MongoDB 驱动程序 (pymongo) 中的限制功能。

【问题讨论】:

    标签: python mongodb asynchronous twisted pymongo


    【解决方案1】:

    “find”创建一个 PyMongo 光标,并且不再做任何工作。 “查找”不会向 MongoDB 服务器发送消息,也不会检索任何结果。除非您像这样迭代光标,否则工作不会开始:

    for doc in cursor:
        print(doc)
    

    或者:

    all_docs = list(cursor)
    

    所以你这样做的方式已经错了:你将创建游标的工作推迟到一个线程,需要推迟,因为它不做网络输入/输出。但是您随后在主线程上使用光标,您确实需要推迟。

    所以我建议如下:

    def find_all():
        # find_one() actually does network I/O
        doc1 = self.mongo_pool.database[collection].find_one(self.my_id)
        # creating a cursor does no I/O
        cursor = self.mongo_pool.database[collection].find().limit(3)
        # calling list() on a cursor does network I/O
        return doc1, list(cursor)
    
    stuff_deferred = deferToThread(find_all)
    

    【讨论】:

    • 很棒的输入!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多