mod_wsgi 如何知道并执行应用程序?

How does mod_wsgi know and execute the application?

我正在安装 Apache/2.2.22 (Debian) mod_wsgi/3.3 Python/2.7.3

我设法执行了 WSGIScriptAlias,但只有顶层模块代码,而不是其中定义的 application

Apache 配置:

LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so

WSGIScriptAlias  /testurl /home/django/test/test/wsgi_test.py

<Directory /home/django/test/test>
<Files wsgi_test.py>
Order deny,allow
Allow from all
</Files>
</Directory>

wsgi_test.py:

#!/usr/bin/python
import sys
print >> sys.stderr, "I'm wsgi_test"

def application(environ, start_response):
        print >> sys.stderr, 'in application'
        status = '200 OK'
        output = 'hello World'
        response_headers = [('Content-type', 'text/plain'),
                            ('Content-Length', str(len(output)))]
        start_response(status, response_headers)
        return [output]

当使用浏览器请求 url 时,wsgi_test.py 脚本被执行("I'm wsgi_test" 出现在 apache 错误日志中)。但是,没有提供任何页面(500 内部服务器错误)并且有一个额外的错误日志条目 脚本过早结束 headers:wsgi_test.py.

作为第二个测试,我使用了一个简单的脚本,它正确地服务于 'Hello World':

wsgi_test2.py:

#!/usr/bin/python
import sys
print 'Content-type: text/plain\n\n'
print 'Hello World'

我的问题: mod_wsgi如何知道并执行应用程序?

从上面的测试,我得出的结论是wsgi_test.py是立即执行的。由于没有可执行代码,只有 application 的定义,脚本不输出任何内容,因此服务器抱怨缺少 html headers。我如何告诉系统 运行 application?

mod_wsgi 模块不会以您可能想的方式执行脚本。也就是说,它不会 运行 它们作为一个程序。

您的 Apache 配置可能已设置,因此扩展名为 .py 的文件作为 CGI 脚本执行,因此 mod_wsgi 实际上并未处理。这将解释您所看到的行为。

要么禁用使 .py 文件成为 CGI 脚本的 AddHandler 指令,要么重命名您的 WSGI 脚本以具有 .wsgi 扩展名并更改 WSGIScriptAlias 指令以匹配。

完成后,mod_wsgi 会将 WSGI 脚本加载到内存中,然后 运行 服务器进程内存中的 Python 代码。所以不能作为单独的程序执行。

如果您确保 Apache 中的 LogLevel 指令设置为 info(如果当前设置为 warn),那么您应该会看到更多由 [=28= 记录的消息] 关于它第一次将 WSGI 脚本加载到 运行 的时间。这将确认 mod_wsgi 正在处理它们。