1

I need to execute Process during request like below

@app.route('/test')
def test_process():
    print "starting new process"
    p = Process(target=do_long_extra_job)
    p.start()

    return "this is response"

do_long_extra_job is on another process, so expected work flow is like this

  1. start a process
  2. response
  3. long running extra job finished

but actual flow is like this

  1. stat a process
  2. long running extra job finished
  3. response

how can I response immediately after starting new process?

4
  • You should look into using a task runner like RQ or Celery for this. Commented Jun 26, 2015 at 3:18
  • @jonafato But I can't use Celery or RQ either. Commented Jun 26, 2015 at 3:25
  • Why are these not options? They're probably better solutions in the long term than rolling your own version using multiprocessing. Commented Jun 26, 2015 at 5:33
  • @jonafato because system admin rejects to install these... :( Commented Jun 26, 2015 at 5:45

1 Answer 1

-1

The apply_async method in the multiprocessing.Pool class may work for you. 'Process' won't work for you in this case since it's a blocking method, meaning that your return statement will not execute until p.start() has finished executing.

Example with apply_async and multiprocessing.Pool:

def do_long_extra_job():
    #some extra long process
    return

@app.route('/test')
def test_process():
    print "starting new process"
    pool = multiprocessing.Pool(processes=1)
    pool.apply_async(do_long_extra_job)
    return "this is response" 
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, but I need to add lines like this, async_result = pool.apply_async(do_long_extra_job), async_result.get(). I don't know why get() is needed but it works.
Ok, It's not working :( Please reject my edit. I knew that get() is blocking and waiting results back, but It works first time... or looks like working.
Finally, I find out that Pool.apply_async is not working on my production environment setup(using uwsgi / nginx). I need to tell my system admin to install Celery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.