Posted under » Apache » Python on 17 April 2021
To run python script by command line, you normally
$ python3 ~/submit_grades.py
When you install LAMP, php is installed with apache and mysql. To run python script over the web, it is slightly harder. First you need to install Python Apache Mod_wsgi. The mod_wsgi is an Apache module used to serve Python scripts over HTTP.
For python 3 you need to install for py3.
$ sudo apt install libapache2-mod-wsgi-py3
Restart Apache. Now create a file on webfolder 'test_wsgi_script.py'.
def application(environ, start_response):
status = '200 OK'
headers = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, headers)
# Returns an iterable containing bytes
return [b"Hello, WSGI World!"]
Now create a configuration file eg. /etc/apache2/conf-available/mod-wsgi.conf with the following contents.
WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py
Enable it.
$ sudo a2enconf mod-wsgi $ sudo systemctl restart apache2
The Python script is ready to serve over Apache. You can test the script by accessing the URL http://fi3fi.com/test_wsgi in a web browser.
You will notice that this applies system wide and may not be ideal if you have several virtual sites or environment. So lets do for a specific vhost.
<VirtualHost *:80>
ServerName fi3fi.com
ServerAdmin webmaster@localhost
WSGIScriptAlias /test_wsgi /var/www/scripts/test_wsgi_script.py
DocumentRoot /var/www/scripts/
Options Indexes FollowSymLinks MultiViews
ErrorLog ${APACHE_LOG_DIR}/error-fi3fi.log
CustomLog ${APACHE_LOG_DIR}/access-fi3fi.log combined
</VirtualHost>
If you want to use django, read this