在 Bottle 应用程序中使用多进程创建多个 Bottle 实例

问题描述

我有一个 Bottle Web 应用程序运行一个很长的任务,为了赢得一些时间,我使用了多处理池。在 webapp 之外(所以只在我的 IDE 中运行代码)它看起来不错,从 54 秒到 14 秒。但是如果我在我的 webapp 上下文中运行我的多处理函数,它只显示 X 次(X 对应于我的池大小):

Bottle v0.12.18 server starting up (using WsgiRefServer())...

示例

ma​​in.py

from bottle import route,run
from functions import runFunction


@route('/')
def index():
    runFunction()
    return "<b>Hello</b>!"

run(host='localhost',port=8083,debug=False,reloader=True)

functions.py

import multiprocessing as mp
import time
import random

def longTask(x):
    print(mp.current_process())
    y = random.randint(1,5)
    print(y)
    time.sleep(y)
    return x**x

def runFunction():
    start_time = time.time()
    pool = mp.Pool(3)
    result = pool.map(longTask,[4,2,3,5,1,2])
    print(result)
    
if __name__ == '__main__':
    runFunction()

如果只在functions.py中运行main,输出为:

<SpawnProcess(SpawnPoolWorker-1,started daemon)>
1
<SpawnProcess(SpawnPoolWorker-3,started daemon)>
4
<SpawnProcess(SpawnPoolWorker-2,started daemon)>
2
<SpawnProcess(SpawnPoolWorker-1,started daemon)>
1
<SpawnProcess(SpawnPoolWorker-1,started daemon)>
2
<SpawnProcess(SpawnPoolWorker-2,started daemon)>
1
<SpawnProcess(SpawnPoolWorker-2,started daemon)>
2
[256,4,27,3125,4]

Process finished with exit code 0

如果您启动您的 Bottle 应用程序并继续访问 http://localhost:8083/,它将输出

Bottle v0.12.18 server starting up (using WsgiRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

Bottle v0.12.18 server starting up (using WsgiRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

Bottle v0.12.18 server starting up (using WsgiRefServer())...
Listening on http://localhost:8083/
Hit Ctrl-C to quit.

我当然在多进程逻辑中遗漏了一些东西,但我找不到什么。知道发生了什么吗?

解决方法

main.py 文件在进程启动期间由 multiprocessing 导入,所有新进程通过调用 run(host=... 生成新的 Bottle 服务器。只需确保在导入文件时不执行 run

if __name__ == '__main__':
    run(host='localhost',port=8083,debug=False,reloader=True)