为什么 gUnicorn 在 运行 个 Flask 时生成 2 个进程

Why gUnicorn spaws 2 process when running a Flask

我是 运行 一个 Flask 应用程序,基本上是从 Twitter 中提取推文。虽然 运行 带有嵌入式 Flask 服务器的应用程序没有问题,但是当 运行 在 gUnicorn 中时,我收到重复的推文,主要是因为我有 2 个线程从 Twitter 接收回调。

例如,如果我使用

启动我的应用程序

python app.py

收到推文时,我得到了预期的输出,看到我在记录器输出中附加了线程信息(第一个参数):

140721974449920 2015-03-12 17:59:13,030 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]
140721974449920 2015-03-12 17:59:14,646 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]
140721974449920 2015-03-12 17:59:49,031 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]

如您所见,时间戳看起来也有效,检查我存储它的 mongo 集合,我发现文档没问题。然后,如果我使用 gunicorn 启动应用程序:

gunicorn app:app -b localhost:8000 --debug

然后查看日志,我可以看到有 2 个不同的线程正在获取数据:

139883969844992 2015-03-12 17:52:05,104 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]
139883961452288 2015-03-12 17:52:05,106 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]
139883969844992 2015-03-12 17:53:36,480 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]
139883961452288 2015-03-12 17:53:36,481 INFO: Got message from streaming Twitter API! [in /home/mosquito/git/opencoast_streamer/app.py:83]

如您所见,发生了一些奇怪的事情……然后我去查看并检查了 gunicorn:

ps aux | grep gunicorn

mosquito 25035  3.1  0.3  54612 12516 pts/1    S    15:31   0:01 /home/mosquito/www/env/bin/python /home/mosquito/www/env/bin/gunicorn app:app -b localhost:8000
mosquito 25606  0.0  0.4  66904 17016 pts/1    R    15:32   0:00 /home/mosquito/www/env/bin/python /home/mosquito/www/env/bin/gunicorn app:app -b localhost:8000
mosquito 25610  0.0  0.0  13220   956 pts/3    S+   15:32   0:00 grep --color=auto gunicorn

因此,我开始认为这与 gUnicorn 有关...知道为什么 gUnicorn 正在为我的 Flask 应用生成 2 个进程吗?

谢谢!

我相信这不是 gUnicorn 的错,而是 Werkzeug 的预期行为。 Werkzeug 有一个 "reloader" 进程来监视文件更改(因此如果它检测到 .py 文件中的更改会重新加载。

有关重新加载器的更多信息go here

为了让您度过难关,我相信在您对 app.run 的调用中添加 use_reloader=Falseapp.run(use_reloader=False) 就可以了。

您还可以查看此 SO answer 了解更多信息。

gunicorn --workers=1 app:app -b localhost:8000 --debug

Source

Gunicorn 总是会生成至少 2 个进程,即使您设置了 --workers=1。其中一个进程是主进程,它生成其他工作进程来处理请求。