2013-07-11 69 views
14

我有個問題,那Django可以做多線程嗎?Can Django可以做多線程工作嗎?

下面是我想要做的:點擊網頁上的按鈕,然後在model.py中有一些函數開始運行,例如,從Internet上抓取一些數據,完成後返回給用戶結果。

我不知道,我要開一個新的線程在model.py執行的功能,有誰能夠告訴我該怎麼辦呢?非常感謝你。

+0

什麼是你想完成?也許你可以做到這一點的前端TECNOLOGIES如AJAX,WebSocket的,魔術小馬... – gipi

+0

什麼是魔術小馬?在谷歌找不到它... –

回答

9
  1. 是的,它可以多線程,但通常使用芹菜來做等效。 You can read about how in the celery-django tutorial.
  2. 這是罕見的,你實際上要強制用戶等待網站。雖然比風險超時更好。

這裏是你描述的一個例子。

User sends request 
Django receives => spawns a thread to do something else. 
main thread finishes && other thread finishes 
... (later upon completion of both tasks) 
response is sent to user as a package. 

更好的辦法:

User sends request 
Django receives => lets Celery know "hey! do this!" 
main thread finishes 
response is sent to user 
...(later) 
user receives balance of transaction 
+58

芹菜是許多用途的矯枉過正。請停止推薦它作爲任何需要不阻止請求/響應的魔術項目。這就像每當有人詢問如何存儲一行文本時推薦RDBMS一樣。 –

+5

@andybak隨意建議一個替代方案。對我來說,這聽起來像是一種合法用途。 – cwallenpoole

+4

取決於細節,但你可以只產生一個線程和輪詢後,您可以使用檢查任務的一個簡單的cron作業,或者如果你需要更多的功能,你可以用幾個「不一樣複雜芹菜」一諸如huey或django-background-tasks之類的項目。 –

0

如果你不想一些矯枉過正的框架添加到您的項目中,你可以簡單地使用subprocess.Popen

def my_command(request): 
    command = '/my/command/to/run' # Can even be 'python manage.py somecommand' 
    subprocess.Popen(command, shell=True) 
    return HttpResponse(status=204) 
相關問題