我对 Gunicorn 完全陌生,我正在尝试在 Gunicorn 上运行我的 Flask 应用程序。我遇到的错误可以复制如下。
import threading
from flask import Flask
def perpectual_background_process():
while True:
True
def start_background_thread():
global extra_thread
extra_thread = threading.Thread(target=perpectual_background_process)
extra_thread.start()
app = Flask(__name__)
@app.route('/')
def hello_world():
return str(extra_thread.is_alive())
if __name__ == '__main__':
start_background_thread()
app.run()
当应用程序在 Flask 服务器上运行时,浏览器会正确显示
True
,但在 Gunicorn 服务器上运行时会返回以下错误。
➜ app_folder gunicorn -b 0.0.0.0:5000 app:app
[2024-01-24 22:05:11 +0800] [65632] [INFO] Starting gunicorn 21.2.0
[2024-01-24 22:05:11 +0800] [65632] [INFO] Listening at: http://0.0.0.0:5000 (65632)
[2024-01-24 22:05:11 +0800] [65632] [INFO] Using worker: sync
[2024-01-24 22:05:11 +0800] [65634] [INFO] Booting worker with pid: 65634
[2024-01-24 22:05:15,612] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 2528, in wsgi_app
response = self.full_dispatch_request()
File "/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1825, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1823, in full_dispatch_request
rv = self.dispatch_request()
File "/opt/anaconda3/lib/python3.8/site-packages/flask/app.py", line 1799, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "/Users/my_name/Downloads/testing/app.py", line 17, in hello_world
return str(extra_thread.is_alive())
NameError: name 'extra_thread' is not defined
似乎应用程序无法在
extra_thread
之前启动 app
。我已经做了一些研究,但我无法找到或提出解决方案来处理这个问题。如何让我的应用程序按预期运行?非常感谢您的时间和帮助!
你只需要在全局范围内定义
extra_thread
:
...
extra_thread
def start_background_thread():
global extra_thread
...
...