Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to run python script from Apache

Tags:

python

apache

I have spent ages trying to figure this out. I'm basically trying to develop a website where I have to execute a python script when the users clicks a specific button. After researching on Stack Overflow and Google, I need to configure Apache to be able to run CGI scripts. I have seen numerous examples of software that can accomplish this, such as mod_wsgi. The problem is that I get extremely confused with the instructions for these softwares, especially for mod_wsgi. I don't understand the instructions at all, and I can't install the software and get anything to work.

If anyone has a very easy method for executing python scripts in Apache, I would greatly appreciate. If anyone would like to explain how to use mod_wsgi, I would greatly appreciate that as well, because as of right now I have no idea how to use it and the installation instructions are confusing the hell out of me.

like image 516
Vishwa Iyer Avatar asked Oct 20 '22 22:10

Vishwa Iyer


1 Answers

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/python
print('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.

like image 71
ppalacios Avatar answered Oct 23 '22 13:10

ppalacios