2013-07-31 67 views
3

只是在這方面掙扎。如果我有一個異步請求處理程序,它在執行期間會調用其他執行某些操作的函數(例如async db查詢),然後他們自己調用「finish」,是否必須將它們標記爲async?因爲如果應用程序的結構與示例類似,則會出現有關多次調用「完成」的錯誤。我想我錯過了一些東西。來自Tornado的調用函數異步

class MainHandler(tornado.web.RequestHandler): 

    @tornado.web.asynchronous 
    @gen.engine 
    def post(self): 
     #do some stuff even with mongo motor 
     self.handleRequest(bla) 

    @gen.engine 
    def handleRequest(self,bla): 
     #do things,use motor call other functions 
     self.finish(result) 

是否所有函數都必須標記爲異步? 謝謝

回答

0

調用結束HTTP請求見docs。其他功能不應該叫'完成'

我想你想做這樣的事情。請注意,有一個額外的PARAM「回調」被添加到異步功能:

@tornado.web.asynchronous 
@gen.engine 
def post(self): 
    query ='' 
    response = yield tornado.gen.Task(
     self.handleRequest, 
     query=query 
    ) 
    result = response[0][0] 
    errors = response[1]['error'] 
    # Do stuff with result 

def handleRequest(self, callback, query): 
    self.motor['my_collection'].find(query, callback=callback) 

更多信息

tornado.gen docs