Web.py Cookbook 简体中文版 - 如何使用web.background
注意!!?web.backgrounder已轉移到web.py 3.X實驗版本中,不再是發行版中的一部分。你可以在這里下載,要把它與application.py放置在同一目錄下才能正運行。
介紹
web.background和web.backgrounder都是python裝飾器,它可以讓某個函式在一個單獨的background線程中運行,而主線程繼續處理當前的HTTP請求,并在稍后報告background線程的狀態(事實上,后臺函式的標準輸出(stdout)被返回給啟動該線程的”backrounder”)。 譯注:我本來想將background thread翻譯為后臺線程,后來認為作者本意是想表達“被background修飾的函式所在的線程”,最后翻譯采用“background線程”
這樣,服務器就可以在處理其他http請求的同時,快速及時地響應當前客戶端請求。同時,background線程繼續執行需要長時間運行的函式。
例子
#!/usr/bin/env python # -*- coding: utf-8 -*- from web import run, background, backgrounder from datetime import datetime; now = datetime.now from time import sleepurls = ('/', 'index',)class index:@backgrounderdef GET(self):print "Started at %s" % now()print "hit f5 to refresh!"longrunning()@background def longrunning():for i in range(10):sleep(1)print "%s: %s" % (i, now())if __name__ == '__main__':run(urls, globals())在請求http://localhost:8080/時,將自動重定向到類似http://localhost:8080/?_t=3080772748的網址(t后面的數字就是background線程id),接下來(在點擊幾次刷新之后)就會看到如下信息:
Started at 2008-06-14 15:50:26.764474 hit f5 to refresh! 0: 2008-06-14 15:50:27.763813 1: 2008-06-14 15:50:28.763861 2: 2008-06-14 15:50:29.763844 3: 2008-06-14 15:50:30.763853 4: 2008-06-14 15:50:31.764778 5: 2008-06-14 15:50:32.763852 6: 2008-06-14 15:50:33.764338 7: 2008-06-14 15:50:34.763925 8: 2008-06-14 15:50:35.763854 9: 2008-06-14 15:50:36.763789提示
web.py在background.threaddb字典中保存線程信息。這就很容易檢查線程的狀態;
class threaddbviewer:def GET(self):for k, v in background.threaddb.items():print "%s - %s" % ( k, v )web.py并不會主動去清空threaddb詞典,這使得輸出(如http://localhost:8080/?_t=3080772748)會一直執行,直到內存被用滿。
通常是在backgrounder函式中做線程清理工作,是因為backgrounder可以獲得線程id(通過web.input()得到”_t”的值,就是線程id),從而根據線程id來回收資源。這是因為雖然background能知道自己何時結束,但它無法獲得自己的線程id,所以background無法自己完成線程清理。
還要注意?How not to do thread local storage with Python 在python中如何避免多線程本地存儲?- 線程ID有時會被重用(可能會引發錯誤)
在使用web.background時,還是那句話--“小心為上”
轉載于:https://www.cnblogs.com/justjavac/archive/2012/11/26/webpy-cookbook-background.html
總結
以上是生活随笔為你收集整理的Web.py Cookbook 简体中文版 - 如何使用web.background的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Inno Setup 打包安裝判斷是否安
- 下一篇: javascript 页面跳转大总结