2016-07-07 54 views
0

在我的Python Twisted应用程序中,我需要从客户端接收数据,执行一些数据库操作,并且 - 取决于数据 - 在单独的线程中运行一些阻止代码。混合推迟和deferToThread在单独的线程中运行阻止代码

到目前为止,我有:

d = get_user(user_id) 

d.addCallback(do_something_with_input_data, input_data) 
d.addCallback(run_blocking_code) 
d.addCallback(save_data_into_db) 
d.addCallback(response_to_client) 

@defer.inlineCallbacks 
def get_user(self, user_id): 
    user = yield get_user_from_db(user_id) 
    defer.returnValue(user) 

def do_something_with_input_data(user, input_data): 
    # do smth... 
    return results 

@defer.inlineCallbacks 
def run_blocking_code(results) 

    threads.deferToThread(run_in_separate_thread, results) 
    return results 

@defer.inlineCallbacks 
def save_data_into_db(results) 
    yield save_in_db(results) 
    def.returnValue('OK') 

def response_to_client(response) 
    # send 'OK' to client 

这是一个很好的方法来调用run_blocking_code()deferToThread()?如果是这样,我怎么能让save_data_into_db()等到线程结束?

回答

1

我会说一般的概念很好。我会添加一些errbacks,而且你还需要调整你的run_blocking_code函数:

@defer.inlineCallbacks 
def run_blocking_code(results) 

    # the `deferToThread` returns a deferred 
    d = threads.deferToThread(run_in_separate_thread, results) 

    # let's wait for it here (need a yield for functions decorated with `inlineCallbacks`) 
    yield d 

    # now return its value to the next function in the callback chain 
    defer.returnValue(d.result)