2015-02-11 26 views
1

我的開發堆棧是Django/Python。 (包括Django-REST框架) 我目前正在尋找方法來做多個不同的API調用。在Python/Django中將多個POST請求作爲多線程提交

client.py 

def submit_order(list_of_orders): 
    //submit each element in list_of_orders in thread 
    for order in list_of_orders: 
     try: 
     response=request.POST(order, "www.confidential.url.com") 
     except: 
     //retry_again 
     else: 
      if !response.status==200: 
       //retry_again 

在上面的方法中,我目前正在逐一提交訂單,我想一次提交所有訂單。其次,如果失敗,我想重新提交x次。 我目前不知道如何實現它。

我正在尋找Python庫或Django應用程序提供的方式,而不是重新發明方向盤。

感謝

+0

你可以看看[django-celery](http://celery.readthedocs.org/en/latest/) – Selcuk 2015-02-11 00:10:07

回答

2

正如@Selcuk說,你可以嘗試django-celery這在我看來是一個推薦的方法,但需要進行一些配置,看了一些手冊。

在另一方面,你可以嘗試使用multiprocessing這樣的:

from multiprocessing import Pool 

def process_order(order): 
    #Handle each order here doing requests.post and then retrying if neccesary 
    pass 

def submit_order(list_of_orders): 
    orders_pool = Pool(len(list_of_orders)) 
    results = orders_pool.map(process_order, list_of_orders) 
    #Do something with the results here 

這將取決於你的需要得到完成,如果你能做到在背景上的要求操作和您的API用戶可以稍後再通知,只需使用django-celery,然後相應地通知用戶,但如果你想要一個簡單的方法來立即作出反應,你可以使用我爲你「原型」的那個。

你應該考慮某種延遲對你的請求的響應(因爲你正在做一些POST請求)。因此,請確保您的POST請求不會增長很多,因爲它可能會影響調用您的服務的API客戶端的體驗。

+1

我正在寫客戶端。我需要同時提交很多POST請求。但是,我認爲你使用多處理技術建議的是重量級和資源密集型的。 – 2015-02-11 01:00:02