简体   繁体   中英

Configure apache to run python (cgi)

i've wampserver with apache 2.4.4 installed in

I've installed python and i created a test file :

#!/Python34/python
print "Content-type: text/html"
print
print "<html><head>"
print ""
print "</head><body>"
print "Hello."
print "</body></html>"

i wanna know how to run this script ?

I personally don't like the way CGI and all this stuff work (slow to spawn processes, need to use some kind of tricks like "fastcgi" to bypass this, etc...)

I think you may build your Python programm as an HTTP server (Use cherrypy for example, or whatever you want.), start your Python program to listen on localhost:whatever, then, from the Apache side, just configure a proxy to localhost:whatever.

Pros:

  • No need for apache to fork a Python process each requests (An expensive operation)
  • You'll change your web server easily (like switch to Nginx) as nginx also support proxying.
  • You'll be able to start multiple Python servers and load balance between them
  • You'll be able to host your python servers on different host to load balance charge
  • You'll be able to completly bypass Apache if you put a Varnish in front of your app to cache results.
  • Cherrypy can automatically reload files if they are changed, no need to restart apache.
  • You'll stick to HTTP, no need to use protocols like fastcgi.
  • Easy to test on your dev machine without Apache, just point your browser to your localhost:whatever

Configuring apache 2 to pass your requests to your python daemon is as easy as:

<VirtualHost *:80>
    ServerName example.com
    ProxyPass / http://localhost:8080/
</VirtualHost>

And an hello world from the cherrypy documentation:

import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

+1 to what Julien Palard says about not using CGI, it's really slow and inefficient. An alternative to running your server standalone and proxying through to it using Apache is to use mod_wsgi, which allows you to run Python processes inside the Apache process. Most web frameworks (Django, Bottle, Flask, CherryPy, web2py, etc) work well with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM