[英]When can I call multiprocess.close() or process.join() after early return in flask function?
我想做什么當 flask 應用程序收到對特定端點的請求(例如 /scale-up)時,由於打開 EC2 實例需要超過 5 分鍾,我嘗試在不同的進程中運行該邏輯並直接向發送請求的用戶發送響應(不要等到該進程打開 EC2 實例)。
但是當這種情況發生時,我不知道什么時候可以 close() 和 join() 進程。
回顧一下,當一個請求進來時,它只會“執行”一個需要很長時間的過程,除此之外我只發送一個 OK 響應。 之后,我怎樣才能關閉並加入這個過程?
我嘗試使用燒瓶的 teardown_request 裝飾器,但這似乎也不是正確的方法。
這是我的代碼。
import multiprocessing
from flask import Flask, Response
from multiprocessing import Pool
app = Flask(__name__)
@app.route(f'/scale-up')
def send_scale_up_request():
try:
p = Pool(4)
p.apply_async(scale_up_instance)
logger.info("Executing to restart the instance...")
return Response("Executing to restart the instance...")
# where can I put p.close() and p.join()??
except Exception as e:
logger.error("Error occured")
logger.error(e)
logger.error(traceback.format_exc(limit=None))
def scale_up_instance():
# turn on EC2 instance using aws sdk(boto3)
.....
非常感謝。 這是我第一次在這里問問題...
沒有理由使用多處理池來運行單個進程,因此也不需要close
和join
。 但即使運行單個Process
,也確實沒有地方或需要撥打電話join
它。 該過程將異步運行並在您當前的請求終止后結束。
更新
為了防止因無法對已啟動的進程進行join
而導致進程失效,請改為將scale_up_instance
作為線程運行。 如果由於某種原因線程不夠,線程可以啟動一個可以加入的進程:
import multiprocessing
from flask import Flask, Response
from threading import Thread
import time
app = Flask(__name__)
@app.route(f'/scale-up')
def send_scale_up_request():
try:
Thread(target=scale_up_instance).start()
logger.info("Executing to restart the instance...")
return Response("Executing to restart the instance...")
except Exception as e:
logger.error("Error occured")
logger.error(e)
logger.error(traceback.format_exc(limit=None))
def scale_up_instance():
# turn on EC2 instance using aws sdk(boto3)
import time
print('starting...')
time.sleep(10)
print('ending.')
# If multiprocessing is required because of GIL restrictions then:
from multiprocessing import Process
p = Process(target=do_scale_up) # defined elsewhere
p.start()
p.join()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.