正如您所说,使用 CGI 是一种不那么简单但在某种程度上简单的方法。
您可以在Apache documentation 和Python CGI module documentation 找到更多信息。
但是,基本上,您必须将服务器设置为运行 cgi sripts。这是通过编辑 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.
然后,您只需在上面设置的目录中添加您的python脚本即可。
请注意,如 Apache 文档所述,脚本的输出必须以 mime 类型的标头开头。
因此,一个 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')
然后,您可以从浏览器调用您的脚本:
http://localhost/cgi-bin/hello.py
请注意,Python 在其 cgi realted 内置模块中有一些好东西。 cgi 模块将为您提供一种处理表单的方法,而 cgitb 将为您提供一种有用的(但不是完美的)调试脚本的方法。有关更多信息,请再次阅读文档。
最后,直接使用 cgi 来运行 python 脚本为您提供了一种处理 http 请求的原始方式。有很多已经完成的框架,比如 flask 和 django,可以轻松地为您提供更多功能。你可以检查一下。