【问题标题】:Using multiprocessing with gunicorn in Flask application在 Flask 应用程序中使用带有 gunicorn 的多处理
【发布时间】:2017-07-27 01:18:00
【问题描述】:

我使用 Gunicorn 和工人类 gevent 制作了一个基本的烧瓶应用程序。我遇到的问题如下。如果我有一个像这样的基本烧瓶应用程序:

from multiprocessing import Pool
import Queue
import random
from threading import Thread
import time

from flask import Flask

app = Flask(__name__)

def f(x):
    return random.randint(1, 6)

def thread_random(queue):
    time.sleep(random.random())
    queue.put(random.randint(1, 6))

def thread_roll():
    q = Queue.Queue()
    threads = []
    for _ in range(3):
        t = Thread(target=thread_random, args=(q, ))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

    dice_roll = sum([q.get() for _ in range(3)])
    return dice_roll

@app.route('/')
def hello_world():
    # technique 1
    pool = Pool(processes=4)
    return 'roll is: %s \n' % sum(pool.map(f, range(3)))

    # technique 2
    return 'roll is: %s \n' % thread_roll()

if __name__ == '__main__':
    app.run(debug=True)

我采用了两种技术,如果我这样运行,技术 1 会破坏 gunicorn:

sudo gunicorn -b 0.0.0.0:8000 app:app --worker-class gevent

但技术 2 不会。我看到这是因为技术 1 依赖于多处理而技术 2 依赖于线程,但我不明白为什么 gevent 工作人员类不允许池?

【问题讨论】:

    标签: python multithreading flask multiprocessing gunicorn


    【解决方案1】:

    如果您使用的是 gevent。您应该尝试使用 monkey_patch。

    http://www.gevent.org/gevent.monkey.html

    【讨论】:

    • 我不知道这个建议是什么意思
    • 如果您使用 gevent,您应该在使用之前先阅读文档。在运行任何 gevent/eventlet 代码之前,这是您应该将其放入代码中的最关键的部分。 Monkey 补丁会将低级调用变为非阻塞。技术 2 在 python 本机线程上运行。如果没有猴子修补它,它将被阻塞。 Monkey patching 会将该线程调用的低级别调用变为非阻塞调用。 (RTMS)
    • 如前所述,我使用的是 gunicorn。 github.com/benoitc/gunicorn/blob/… gevent 工作人员在开始之前调用了 monkey.patch_all(),所以除了在为每个工作人员运行 gunicorn 时调用它之外,我没有理由将它添加到我的代码中。
    猜你喜欢
    • 2021-12-24
    • 2018-07-08
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2019-10-03
    • 2021-02-07
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多