1

There's multiple ways, and not clear tutorials or anything online on how to run a fundamentally basic python script with apache.

mod_python? cgi? wsgi?

Does something need to be installed with python?

It's really confusing. I've been working on it for hours.

1 Answer 1

2

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.

  1. Issue 1 - Conf file which does the mapping - /etc/apache2/conf-available/wsgi.conf
  2. 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
  3. 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

  1. Install mod_wsgi for Apache2

    sudo apt install libapache2-mod-wsgi

  2. Restart Apache to refresh all updates

    apachectl restart

  3. Create the mapping file

    vi /etc/apache2/conf-available/wsgi.conf

  4. Update the mapping file with url and local path

    WSGIScriptAlias /mangojuice /etc/www/superhightechjuice/mango.py

  5. 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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.