我可以依靠在WSGI运行时读取的Python应用程序模块中初始化全局变量和调用关闭挂钩吗?
我是Python,WSGI和Flask的新手。我想在HTTP请求处理程序中与Redis通信,所以我正在考虑将Redis客户端实例存储在全局变量中(因为可以安全地从多个线程使用)。根据下面的示例,它似乎可以按我的意愿运行(至少对于Gunicorn而言),但是我熟悉Java EE环境,在该环境中,一切都没有希望的,所以我希望得到专家的意见。
注意,我不是在解决问题,而是试图了解WSGI中的工作原理,因此我对在WSGI应用程序中共享状态的框架或其他方法不感兴趣。我只是想知道如果我这样共享(本地过程)数据是否会出错?
WSGI应用程序dispatch.py
:
#!/usr/bin/python3
import atexit, flask
x = 0
atexit.register(lambda : print('x = {}'.format(x)))
app = flask.Flask(__name__)
@app.route('/')
def get():
global x
x += 1 # thread unsafe, not a real-world example
return 'x = {}\n'.format(x)
端子1:
% gunicorn -w4 dispatch:app
[2018-11-24 00:44:55 +0100] [10774] [INFO] Starting gunicorn 19.9.0
[2018-11-24 00:44:55 +0100] [10774] [INFO] Listening at: http://127.0.0.1:8000 (10774)
[2018-11-24 00:44:55 +0100] [10774] [INFO] Using worker: sync
[2018-11-24 00:44:55 +0100] [10779] [INFO] Booting worker with pid: 10779
[2018-11-24 00:44:55 +0100] [10780] [INFO] Booting worker with pid: 10780
[2018-11-24 00:44:55 +0100] [10781] [INFO] Booting worker with pid: 10781
[2018-11-24 00:44:55 +0100] [10782] [INFO] Booting worker with pid: 10782
端子2:
% curl localhost:8000
x = 1
% curl localhost:8000
x = 1
% curl localhost:8000
x = 2
% curl localhost:8000
x = 1
% curl localhost:8000
x = 3
% curl localhost:8000
x = 2
% curl localhost:8000
x = 3
% curl localhost:8000
x = 1
端子1:
^C[2018-11-24 00:52:44 +0100] [12859] [INFO] Handling signal: int
[2018-11-24 00:52:45 +0100] [12863] [INFO] Worker exiting (pid: 12863)
[2018-11-24 00:52:45 +0100] [12864] [INFO] Worker exiting (pid: 12864)
[2018-11-24 00:52:45 +0100] [12865] [INFO] Worker exiting (pid: 12865)
x = 3
x = 3
x = 1
[2018-11-24 00:52:45 +0100] [12866] [INFO] Worker exiting (pid: 12866)
x = 2
[2018-11-24 00:52:45 +0100] [12859] [INFO] Shutting down: Master