Easiest Way To Run Python Script From Apache
Solution 1:
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.
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.
Then, you just need to add your python script in the directory that you set above.
Note that the output from your script must be preceded by a mime-type header, as Apache documentation says.
So, a hello world script could be named hello.py and its content could be:
#!/usr/bin/pythonprint('Content-type: text/html') # the mime-type header.print() # header must be separated from body by 1 empty line.print('Hello world')
Than, you can call your scrit from a browser:
http://localhost/cgi-bin/hello.py
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.
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.
Post a Comment for "Easiest Way To Run Python Script From Apache"