且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Apache运行python脚本的最简单方法

更新时间:2022-01-16 09:20:54

一种方法,不是那么容易,但在某种程度上却很简单,就是使用CGI.您可以在 Apache文档

One way, not so easy but simple in some way, is to use CGI, as you said. You can find more information on Apache documentation and Python CGI module documentation.

但是,基本上,您必须将服务器设置为运行cgi sripts.这是通过编辑httpd.conf或.htaccess文件来完成的:对于第一个选项,请添加或取消注释以下内容:

But, basically, you have to set your server to run cgi sripts. This is done by editing httpd.conf or a .htaccess file: For the first option, add or uncomment the follow:

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脚本即可.

Then, you just need to add your python script in the directory that you set above.

请注意,如Apache文档所述,脚本输出必须带有mime类型的标头.

Note that the output from your script must be preceded by a mime-type header, as Apache documentation says.

因此,一个hello world脚本可以命名为hello.py,其内容可以是:

So, a hello world script could be named hello.py and its content could be:

#!/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')

然后,您可以通过浏览器致电您的scrit:

Than, you can call your scrit from a browser:

http://localhost/cgi-bin/hello.py

请注意,Python在其cgi realized内置模块中具有一些优点.cgi模块将为您提供处理表单的方法,而cgitb将为您提供一种有用的(但不是完美的)调试脚本的方法.有关更多信息,请再次阅读文档.

Note that Python has some goodies inside its cgi realted builtin modules. The cgi module will give you a way to handle forms, and cgitb will give you a helpful (but not perfect) way to debug your script. For more on that, read the documentation again.

最后,直接使用cgi运行python脚本为您提供了处理http请求的原始方法.有很多已经完成的框架,例如flask和django,可以轻松为您提供更多功能.您可以检查一下.

Finally, using cgi directly to run python scripts gives you a raw way to work with http requests. There is a lot of already done frameworks, like flask and django, that gives you more power easily. You could check that.