Configure Apache to use Python just like CGI PHP

橙三吉。 提交于 2019-12-02 10:26:25

" So maybe it is not possible, but then I'm curious why this is the case?"

Correct. It's not possible. It was never intended, either.

Reason 1 - Python is not PHP. PHP -- as a whole -- expects to be a CGI. Python does not.

Reason 2 - Python is not inherently a CGI. It's an interpreter that has (almost) no environmental expectations.

Reason 3 - Python was never designed to be a CGI. That's why Python is generally embedded into small wrappers (mod_python, mod_wsgi, mod_fastcgi) which can encapsulate the CGI environment in a form that makes more sense to a running Python program.

You can use any type of executable as cgi. Your problem is in your apache config, which looks like you just made it up. Check the apache docs for more details, but you don't need the Action and AddType.

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

Then drop the following into your cgi-bin:

#!/usr/bin/python
# test.py
print "Content-Type: text/html\n\n"
print "Test"

Make sure it's executable, and see the result at /cgi-bin/test.py

The error "Premature end of script headers:" can occur if the .py file was edited in a Windows program that uses CRLF characters for line breaks instead of the Unix LF.

Some programs like Dreamweaver have line-break-type in preferences. Notepad also uses CRLF.

If your host has a file editor, you could test by backspacing the current linebreaks and reentering them through that editor which would change any CRLF to LF only. Notepad++ can use LF only.

When you open for example http://localhost/test.py you expect that Apache will somehow start process /usr/bin/python /var/www/test.py (i.e the interpreter with single command line argument). But this is not what happens because Apache calls the cgi script with no arguments. Instead it provides all the information through environment variables which are standardized by CGI.

As others have pointed out using python as plain cgi is inefficient but if for educational reasons you would still like to do it you can try this.

Assuming that the default Apache cgi-bin settings are active you can create a simple wrapper named python (or whatever you choose) in your /usr/lib/cgi-bin with the following contents:

#!/usr/bin/python
import os
execfile(os.environ['PATH_TRANSLATED'])

Don't forget to make it executable: chmod a+x /usr/lib/cgi-bin/python

Put these in you Apache config:

AddType application/python .py
Action application/python /cgi-bin/python

Now when you open http://localhost/test.py Apache will execute /cgi-bin/python with no arguments but with filled in CGI environment variables. In this case we use PATH_TRANSLATED since it points directly to the file in the webroot.
Calling execfile interprets that script inside the already opened python process.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!