正如您所说,一种方法是使用 CGI,虽然不太容易,但在某种程度上很简单。
您可以找到更多信息阿帕奇文档 http://httpd.apache.org/docs/current/howto/cgi.html and Python CGI 模块文档 https://docs.python.org/3.4/library/cgi.html.
但是,基本上,您必须将服务器设置为运行 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.
然后,您只需将 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')
然后,您可以从浏览器调用脚本:
http://localhost/cgi-bin/hello.py
请注意,Python 在其 cgi 相关的内置模块中有一些好东西。 cgi 模块将为您提供一种处理表单的方法,而 cgitb 将为您提供一种有用的(但不是完美的)方法来调试脚本。有关更多信息,请再次阅读文档。
最后,直接使用 cgi 运行 python 脚本为您提供了一种处理 http 请求的原始方法。有很多已经完成的框架,例如 Flask 和 django,可以轻松地为您提供更多功能。你可以检查一下。