2010-11-10 63 views
1

我在django powered站點上有一個上傳頁面。最終用戶上載該頁面中的文檔。該上傳文檔的後端處理可能需要幾分鐘的時間。我如何在後端處理多個最終用戶的請求?我曾想過爲每個最終用戶的請求使用線程。然而,我發現在編碼方面很困難,一旦用戶上傳文件,我該如何創建一個新線程。示例示例或演示將受到高度讚賞。 提前感謝您!!!在python中使用線程處理多個最終用戶

回答

1

沒有更多的信息,它很難說什麼,但線程聽起來像一個合理的想法。在Python中創建一個線程,你做到以下幾點:

from threading import Thread 
class Worker(Thread): 
    def __init__(self): 
     Thread.__init__(self) #Runs the thread's constructor 

    #Method that is run when the new thread starts 
    def run(self): 
     #Whatever data processing you have to do can go here 
     while True: 
      print "Hello from Worker" 

w = Worker() 
w.start() #Starts a new thread which executes the object's run function 
+0

謝謝你的建議。我是否必須使用回調處理程序,以便如果任何用戶上載文檔,此處理程序會自動爲該用戶的請求生成一個新線程? – consumer 2010-11-10 09:44:55

+0

如果您正在異步上傳文件(例如,使用Ajax),並且可以在完成文件處理(如將用戶重定向到新頁面)時使用回調在Javascript中執行某些客戶端操作。 – JohnS 2010-11-10 20:45:25

2

的另一種方式啓動一個線程是給你的可調用的Thread構造,像這樣:

from threading import Thread 

processing_thread = Thread(target=your_heavy_lifting_function_name) 
processing_thread.start()