在Python / Django中将多个POST请求作为多线程提交

时间:2015-02-11 00:06:17

标签: python django multithreading rest

我的开发堆栈是Django/Python。 (包括Django-REST框架) 我目前正在寻找方法来进行多个不同的API调用。

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应用程序提供的方法,而不是重新发明轮子。

由于

1 个答案:

答案 0 :(得分: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客户端的体验。