鍍金池/ 問答/Python  Linux/ tornado如何把異步函數(shù)傳遞到模板里面?

tornado如何把異步函數(shù)傳遞到模板里面?

我的模板里面是直接for遍歷后端的一個函數(shù)A,這個函數(shù)A會查詢數(shù)據(jù)庫并返回查詢出來的數(shù)據(jù)(dict),數(shù)據(jù)庫是mongodb,現(xiàn)在我用motor的異步方式來改寫函數(shù)A,然后查詢出來的數(shù)據(jù)用gen.Return()返回,可是這樣返回的是Future對象,模板沒辦法直接用,必須再yield一次才能獲得可用的數(shù)據(jù)。 我現(xiàn)在需要的是模板里面for遍歷的函數(shù)是可以直接返回一個可迭代對象的,下面上代碼:

@tornado.gen.coroutine
def get(self, objid):
    ... 省略邏輯 ...
    self.render( "article.html", get_article=self.get_article )

@tornado.gen.coroutine
def get_article(self, number, thumb, desc, cat, rand):
    """ 
        下面的a變量會異步獲取到所查詢的數(shù)據(jù),F(xiàn)uture封裝過的對象
        do_get_article_list函數(shù)也是用tornado.gen.Return返回的 
    """
    a = yield do_get_article_list(5, 1, 1, '', 1)
    tornado.gen.Return(a)
    
    """ 
        其實(shí)直接yield就可以獲取到異步返回的數(shù)據(jù),但是我要把這個數(shù)據(jù)傳遞到模板里面就不知道怎么弄了
    """
回答
編輯回答
命多硬

直接return a就行了吧,沒必要用gen.Return

2018年2月5日 21:41