我花了很长时间试图弄清楚这一点。我基本上正在尝试开发一个网站,当用户单击特定按钮时,我必须在其中执行 python 脚本。在研究了 Stack Overflow 和 Google 之后,我需要配置 Apache 以便能够运行 CGI 脚本。我见过许多可以实现此目的的软件示例,例如mod_wsgi。问题是我对这些软件的说明感到非常困惑,尤其是mod_wsgi。我根本不理解说明,也无法安装该软件并让任何东西运行。
如果有人有一个非常简单的方法在 Apache 中执行 python 脚本,我将不胜感激。如果有人想解释如何使用 mod_wsgi,我也会非常感激,因为到目前为止我不知道如何使用它,而且安装说明让我很困惑。
正如您所说,一种方法是使用 CGI,虽然不太容易,但在某种程度上很简单。您可以在Apache 文档和Python CGI 模块文档上找到更多信息。
但是,基本上,您必须将服务器设置为运行 cgi 脚本。这是通过编辑 httpd.conf 或 .htaccess 文件来完成的:对于第一个选项,添加或取消注释以下内容:
LoadModule cgi_module modules/mod_cgi.so
ScriptAlias /cgi-bin/ /usr/local/apache2/cgi-bin/ # update the second location according to your configuration. It has to be a place where apache is allow to use, otherwise see apache documentation for setting another directory.
Run Code Online (Sandbox Code Playgroud)
然后,您只需将 python 脚本添加到上面设置的目录中即可。
请注意,脚本的输出前面必须带有 mime 类型标头,如 Apache 文档所述。
因此,hello world 脚本可以命名为 hello.py,其内容可以是:
#!/usr/bin/python
print('Content-type: text/html') # the mime-type header.
print() # header must be separated from body by 1 empty line.
print('Hello world')
Run Code Online (Sandbox Code Playgroud)
然后,您可以从浏览器调用脚本:
http://localhost/cgi-bin/hello.py
Run Code Online (Sandbox Code Playgroud)
请注意,Python 在其 cgi 相关的内置模块中有一些好东西。cgi 模块将为您提供一种处理表单的方法,而 cgitb 将为您提供一种有用的(但不是完美的)方法来调试脚本。有关更多信息,请再次阅读文档。
最后,直接使用 cgi 运行 python 脚本为您提供了一种处理 http 请求的原始方法。有很多已经完成的框架,例如 Flask 和 django,可以轻松地为您提供更多功能。你可以检查一下。