gunicorn是否应该在systemd service unit config中设置PATH和VIRTUALèENV环境变量来为Flask应用程序提供服务?

2024-10-01 07:43:30 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用gunicorn为Flask应用程序提供服务时,我假设应该在gunicorn myapp:app之前激活venv,因为gunicorn与构成该应用程序的其他包和代码一起安装在venv中。在使用flask runpython myapp.py运行应用程序的场景中,需要首先激活venv(在我读过的每个教程和书籍中),因此在我看来,gunicorn的情况没有什么不同的理由。你知道吗

当谈到让gunicorn成为systemd服务单元时,我知道在这个场景中没有办法像在交互式shell中那样“激活一个venv”,我能想到的最接近的事情就是把Environment="PATH=/PathToMyApp:other_default_path_var_contents"Environment="VIRTUAL_ENV=/PathToMyApp/.venv"ExecStart=/PathToMyApp/.venv/bin/gunicorn myapp:app一起放在配置中。你知道吗

然而,我发现我读过的教程中几乎没有一本像我想的那样添加这些环境选项。这些教程是不是就错了,或者环境变量对于虚拟环境中的gunicorn来说无关紧要?如果是后者,为什么?与flask runpython myapp.py病例有什么区别?你知道吗


Tags: run代码pyapp应用程序flaskenvironmentvenv
1条回答
网友
1楼 · 发布于 2024-10-01 07:43:30

查看官方的gunicorn文档,^{}一节说您应该定义:

WorkingDirectory=/PathToMyApp
ExecStart=/PathToMyApp/.venv/bin/gunicorn myapp:app

这应该足够了,而不必设置PATHVIRTUAL_ENV环境变量。你知道吗

Are those tutorials just wrong about this, or the environment variables are insignificant regarding gunicorn in a virtual environment? If it's the latter, why is that? What's the difference from flask run and python myapp.py cases?

当您在shell中激活virtual env运行python myapp.py时,它实际上正在运行virtual env的bin目录中的python解释器。您可以通过以下方式演示这一点:

这将显示您的系统:

/tmp $ which python
/usr/local/bin/python

激活venv:

/tmp $ . venv/bin/activate
(venv) /tmp $

这将在venv中显示python解释器:

(venv) /tmp $ which python
/tmp/venv/bin/python

此外,当您cat venv/bin/gunicorn时,bang行指向该venv中的python解释器:

#!/tmp/venv/bin/python3

因此,当您在systemd单元文件中将它指定为ExecStart(或者在没有激活venv的情况下直接执行venv/bin/gunicorn)时,它实际上是用venv/bin/python3运行的,这反过来使安装在该venv中的所有依赖项对进程可用。你知道吗

相关问题 更多 >