GangstaGraham
GangstaGraham

Reputation: 9355

Perform Task Directly After Returning JSON

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?

Upvotes: 0

Views: 1174

Answers (2)

Arsh Singh
Arsh Singh

Reputation: 2116

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

Upvotes: 5

Paolo Casciello
Paolo Casciello

Reputation: 8202

Yes, you need a task queue. There are a couple of options.

Look at this other question: uWSGI for uploading and processing files

And of course your code is wrong since once you return your terminating code execution of that function you're in.

Upvotes: 0

Related Questions