返回JSON后直接执行任务 [英] Perform Task Directly After Returning JSON

查看:165
本文介绍了返回JSON后直接执行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当移动应用程序请求某些数据时,我需要执行一项任务。用户不需要马上执行任务,但在接下来的2分钟内可能需要它。



我对Python / web dev还是比较新的,所以我不是相当确定如何做到这一点。



我不希望用户等待执行的任务,则可能需要30秒,但我仍然宁愿快30秒。



是否有我可以发送回应,以便用户立即获得所需的信息,然后这个任务是在发送JSON之后立即执行的。

是否可以发送一个响应给请求数据而不使用return的移动应用程序,方法可以继续执行用户不需要等待的任务?

  @ app.route(' / image /< image_id> /')
def images(image_id):
#获取资源(不必要的代码被移除)
返回响应(js,status = 200,mimetype ='application / json')
#一旦JSON响应返回,做一些行动
#(我想要做什么,但不知道如何让它工作






第二个想法也许我需要以某种方式异步执行此操作,所以它不会阻塞路由器(但它仍然需要在返回JSON后立即完成)



UPDATE - 回应一些答案

对于我来说,执行这样的任务,是一个在Heroku上的Worker服务器推荐/必须还是有另一个,更便宜的方法来做到这一点?


$ p $ t =线程.thread(target = some_function,args = [argument])
t.setDaemon(False)
t.start()

您还应该查看芹菜python-rq


I need to perform a task whenever the mobile app requests certain data. The user does not need the task performed right away, but may need it within the next 2 minutes.

I am still fairly new to Python / web dev so I am not quite sure how to accomplish this.

I don't want the user to wait for the task performed, it'll probably take 30 seconds, but I'd still it rather be 30 seconds faster.

Is there anyway that I can send a response, so that the user gets the required info immediately, and then the task is performed right after sending the JSON.

Is it possible to send a Response to the mobile app that asked for the data without using return so that the method can continue to perform the task the user does not need to wait for?

@app.route('/image/<image_id>/')
def images(image_id):
   # get the resource (unnecessary code removed)
   return Response(js, status=200, mimetype='application/json')
   # once the JSON response is returned, do some action
   # (what I would like to do somehow, but don't know how to get it to work


On second thought maybe I need to do this action somehow asynchronously so it does not block the router (but it still needs to be done right after returning the JSON)


UPDATE - in response to some answers

For me to perform such tasks, is a Worker server on Heroku recommended / a must or is there another, cheaper way to do this?

解决方案

you can create a second thread to do the extra work :

t = threading.Thread(target=some_function, args=[argument])
t.setDaemon(False)
t.start()

you should also take a look at celery or python-rq

这篇关于返回JSON后直接执行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆