0

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?

GangstaGraham
  • 8,865
  • 12
  • 42
  • 60
  • I realize that usually more code is required, but I am clueless as to how to do this, as until now, I always thought that the JSON is returned at the end, so I never learned how to do it otherwise. Hope you don't mind. :P – GangstaGraham Aug 25 '13 at 15:41

2 Answers2

5

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

Arsh Singh
  • 2,038
  • 15
  • 16
  • Hmm..I'm on Heroku, so for me to do this, is a Worker server a must, or is there another way around this – GangstaGraham Aug 25 '13 at 16:29
  • you don't require a worker server, just "import threading" and use the code above replacing 'some_function' and 'arguement'. I haven't tried this on heroku, but the docs say you can spawn threads: https://devcenter.heroku.com/articles/python-faq#can-i-spawn-and-control-threads-and-subprocesses – Arsh Singh Aug 25 '13 at 17:14
  • This seems like a good solution for me, +1 for now, once I get it all implemented I'll add a checkmark! – GangstaGraham Aug 27 '13 at 22:21
0

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.

Community
  • 1
  • 1
Paolo Casciello
  • 7,982
  • 1
  • 43
  • 42