简体   繁体   中英

Python Flask sending response immediately

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?

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM