在 linux 中使用 apache 和 mod_wsgi 配置 Python flask 应用程序

Posted

技术标签:

【中文标题】在 linux 中使用 apache 和 mod_wsgi 配置 Python flask 应用程序【英文标题】:Configure Python flask application with apache and mod_wsgi in linux 【发布时间】:2016-08-12 11:52:49 【问题描述】:

我在应用程序帐户下有一个 linux apache 2.4.12 和 mod_wsgi 4.5.2(mod_wsgi.so 安装到 apache)。 Apache 在应用程序帐户下的 8050 端口下运行。按照此链接测试 mod_wsgi 工作:http://modwsgi.readthedocs.org/en/develop/user-guides/quick-configuration-guide.html#wsgi-application-script-file,我输入了我的 URL:http://mytest.mydomain.com:8050/myapp。它显示“Hello World”,所以它表明我的 mod_wsgi 安装工作正常。接下来,我尝试查看是否可以使烧瓶应用程序正常工作。

我在 /home/myuserId/wsgi 下创建了简单的 hello.py 文件:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World!'

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

然后我创建了一个简单的 wsgi 文件:

import sys, os
sys.path.insert(0, "/home/myuserId/wsgi")

from hello import app as application

然后我遵循了其他建议,包括http://flask.pocoo.org/docs/0.10/deploying/mod_wsgi/,将我的 apache http.conf 文件与 virtualhost 配置为:

<VirtualHost *:8050>

  # ServerName www.example.com

  WSGIDaemonProcess hello user=appuser group=appuser threads=5
  WSGIScriptAlias / /home/myuserId/wsgi/hello.wsgi

 <Directory /home/myuserId/wsgi>
    WSGIProcessGroup hello
    WSGIApplicationGroup %GLOBAL
    Require all granted
    Options +ExecCGI
    AddHandler wsgi-script .wsgi
 </Directory>
</VirtualHost>

我保存了 httpd.conf 文件并重新启动了 apache 没有错误。当我在 chrome 中输入 URL:http://mytest.mydomain.com:8050/hello 或 http://mytest.mydomain.com:8050/hello_world 时,我得到了这个错误:

**Not Found**

The requested URL /hello was not found on this server.
Apache/2.4.12 (Unix) mod_wsgi/4.5.2 Python/2.7.9 Server at mytest.mydomain.com port 8050. 

我的问题是:

    是我的配置错误吗? 上述 hello flask 应用程序使用的正确 URL 是什么? 尝试WSGIScriptAlias /hello /home/myuserId/wsgi/hello.wsgi 挂载hello 应用程序,但也未找到。 对于flask app,为什么conf文件一定要在VirtualHost中配置app?

【问题讨论】:

【参考方案1】:

您没有使用主机名指定 ServerName 指令。因此,它将与该 VirtualHost 不匹配,而是回退到它在 Apache 配置文件中找到的第一个 VirtualHost。

【讨论】:

我注释掉了 VirtualHost 标签,它起作用了。然后使用 VirtualHost,我添加了 ServerName mytest.mydomain.com 但它不起作用。但是由于您提到了 VirtualHost,我有另一个 Web 应用程序配置了这样的反向代理: ProxyPreserveHost On ProxyPass localhost:8040/mywebappProxyPassReverse localhost:8040/mywebapp。当我注释掉这个 VirtualHost 时,wsgi virtualHost 工作了。我怎样才能让两者一起工作?非常感谢您的回复和提供 mod_wsgi。 如果在相同的侦听器端口上但为不同的主机名,则为每个设置不同的 ServerName。否则,如果两个 VirtualHost 覆盖 URL 命名空间的不同部分,则将它们合并为一个。

以上是关于在 linux 中使用 apache 和 mod_wsgi 配置 Python flask 应用程序的主要内容,如果未能解决你的问题,请参考以下文章

weblogic11g使用apache2.2做软负载以及session复制的配置

linux系统中如何解决 Apache mod_proxy_http模块超时处理信息泄露的漏洞? CVE-2010-2068

Apache Rewrite(mod_rewrite)无法重写,如果目录名与root下的另一个目录相同,例如Linux上的“lib”

如何在windows7上配置apache和mod

mod_rewrite 在 Linux 中有效,但在 Windows 中无效

在linux上安装Mod_jk以在tomcat前面运行apache的最佳方法是啥