Flow
Client accesses a web page, say http://example.com/mangojuice (issue 1). Your server (apache) should know mangojuice referes to /etc/www/superhightechjuice/mango.py. Now this python file should be executed (issue 2). Apache should know .py is supposed to be executed and not served plain. But Python does not know when to wakeup and run. So another entity is needed (issue 3).
Solutions to the three issues (interfaces) are handled by mod_wsgi:
WSGI is inherited from the CGI concept (which was used for executing perl scripts and php scripts) to extend to Python scripts (with additional features). mod_wsgi is how Graham Dumpleton implemented it in Apache and is now a standard.
- Issue 1 - Conf file which does the mapping - /etc/apache2/conf-available/wsgi.conf
- Issue 2 - Install mod_wsgi - during installation, it updates apache configuration files to inform that .py should be executed; along with a host of other things
- Issue 3 - Function - application
Code
def application(environ, start_response):
status = '200 OK'
message = b"Hello World" #Prefix b is useful to convert string to bytestring, which is needed by HTTP
response_header = [('Content-type', 'text/html')]
start_response(status, response_header)
return [message]
Reason
When you setup mod_wsgi, it solves issue 1 by having a mapping file wsgi.conf. It solves issue 2 by updating .conf file of apache and also other OS based settings. For Issue 3, it tells apache, I am a middleware whenever I see reference to 'application', I will inform you and you both can talk (Apache and Python). This is how mod_wsgi helps.
Steps to setup mod_wsgi
- Install mod_wsgi for Apache2
sudo apt install libapache2-mod-wsgi
- Restart Apache to refresh all updates
apachectl restart
- Create the mapping file
vi /etc/apache2/conf-available/wsgi.conf
- Update the mapping file with url and local path
WSGIScriptAlias /mangojuice /etc/www/superhightechjuice/mango.py
- Create the actual code at /etc/www/superhightechjuice/mango.py
Code sample same as mentioned above. start_response tells mod_wsgi that requests are incoming. mod_wsgi talks with Apache and lets your code through.
Reference:
Official mod_wsgi documentation