Use mod_wsgi to run Python as a web application on CentOS 7
Learn how to install and use Apache's mod_wsgi module to run Python scripts in a web page. This Apache module can be used to serve web pages written in Python, or to render web pages with embedded Python scripts.
mod_wsgi is a particularly good choice for web developers who are accustomed to the way Apache handles PHP. If you want the power and flexibility of Python, but you want it to work like PHP on the web, mod_wsgi is a simple answer.
Requirements
- A Cloud Server running Linux (CentOS 7).
- Apache installed and running.
- A basic familiarity with Python.
- Unlimited traffic
- Fast SSD NVMe storage
- Free Plesk Web Host Edition
<code>mod_wsgi</code> vs <code>mod_python</code>
Many users are confused about the difference between mod_wsgi and mod_python. Both Apache modules have roughly the same effect: They let you run Python modules in a web page.
Although mod_python has a more robust set of features, mod_wsgi is under far more active support and development. Therefore, we recommend mod_wsgi for most users.
Install mod_wsgi
Update your system:
Install mod_wsgi with the command:
Restart Apache:
Verify that the module is loaded:
The server will respond with:
Configure Apache
For security reasons, the Python scripts should be stored in a directory which is not available on the web. Create this directory:
Set Apache as the owner of this directory, so that it can access the files:
We will use WSGIScriptAlias to configure an alias to the script. Access rights will also need to be granted to the directory where the script is located.
Create an Apache configuration file for an example "Hello World" script, and open it for editing:
Put the following content into this file:
Save and exit the file. Then restart Apache:
- Automatic backup & easy recovery
- Intuitive scheduling and management
- AI-based threat protection
Create a test script
We will use the official recommended mod_wsgi Hello World test script for this example.
Create the file and open it for editing:
Put the following content into this file:
Save and exit the file. Then set Apache as the owner of this file, so that it can be accessed:
View this file in a browser at the URL http://example.com/helloworld. You will see the message "Hello World!"