2017-10-28 95 views
-1

我有一個函數,可以獲取我選擇使用financial google的任何貨幣的當前價格,我想多線程,因此我可以單獨發送任何請求。如何在Flask中多線程函數?

這裏是我的代碼

def currency_converter(amount, currency): 
    url = 'https://finance.google.com/finance/converter?a={}&from=KGS&to={}&meta=ei%3DmSr0WeHCCYvBsAH8n6OIBA'.format(amount, currency) 
    urlHandler = urllib2.urlopen(url) 
    html = urlHandler.read() 
    bsoup = BeautifulSoup(html, 'lxml') 
    num = bsoup.find('span').text.split()[0] 
    return float(num) 

@main_route.app_template_filter('currency_converter') 
def thread_me(amount, currency): 
    t = threading.Thread(target=currency_converter, args=[amount, currency]) 
    t.start() 
    t.join() 
    return t 

這裏是如何運行我的模板中的過濾器:

{{ product.price|float|currency_converter('RUB') }} руб

我在這裏返回噸價,我要回來自api的數據,請問我該怎麼做?

另一個問題,我忘了提及,如果我打開任何產品頁面的時間約10秒的頁面!

回答

0

你應該儘量多處理來代替:

from multiprocessing.pool import ThreadPool 

#currency_converter code 

@main_route.app_template_filter('currency_converter') 
def thread_me(amount, currency): 
    pool = ThreadPool(processes=1) 

    result = pool.apply_async(currency_converter, (amount, currency)) 

    return result.get() 
+0

它的工作,但加載頁面時,爲什麼我收到的延遲? ,有沒有什麼辦法可以在沒有任何延遲的情況下完成? – swordfish

+0

它可能是任何東西。我會建議在代碼塊的前後打印時間,以查明確切地說明了造成它的原因需要多長時間。 – gommb

+0

頁面內我正在運行過濾器約10倍,所以我可以在同一時間獲得所有的產品價格,也許這是什麼原因導致延遲? – swordfish

相關問題