Python uWSGI Installation and Configuration
This article primarily introduces how to deploy simple WSGI applications and common web frameworks.
Taking Ubuntu/Debian as an example, first install the dependencies:
Installing uWSGI with Python
Section titled “Installing uWSGI with Python”1. Via pip:
2. Download the installation script:
This installs the uWSGI binary to /tmp/uwsgi, which you can modify.
3. Source code installation:
After installation, you will get a uwsgi binary file in the current directory.
First WSGI Application
Section titled “First WSGI Application”Let’s start with a simple “Hello World”. Create a file foobar.py with the following code:
The uWSGI Python loader will search for the default function named application.
Next, we start uWSGI to run an HTTP server, deploying the application on HTTP port 9090:
Adding Concurrency and Monitoring
Section titled “Adding Concurrency and Monitoring”By default, uWSGI starts a single process and a single thread.
You can add more processes with the –processes option, or add more threads with the –threads option, or use both simultaneously.
The above command will spawn 4 processes, each with 2 threads.
If you want to perform monitoring tasks, you can use the stats subsystem. The monitoring data format is JSON:
We can install uwsgitop (similar to the Linux top command) to view monitoring data:
Combining with Web Servers
Section titled “Combining with Web Servers”We can combine uWSGI with the Nginx web server to achieve higher concurrency performance.
A common nginx configuration is as follows:
The above code means that web requests received by nginx are passed to the uWSGI service on port 3031 for processing.
Now, we can generate uWSGI to use the uwsgi protocol locally:
If your web server uses HTTP, then you must tell uWSGI to use the http protocol locally (this is different from –http which generates its own proxy):
Deploying Django
Section titled “Deploying Django”Django is the most commonly used Python web framework. Assuming the Django project is located at /home/foobar/myproject:
–chdir is used to specify the project path.
We can turn the above command into a yourfile.ini configuration file:
Then you only need to execute the following command:
Deploying Flask
Section titled “Deploying Flask”Flask is a popular Python web framework.
Create a file myflaskapp.py with the following code:
Execute the following command: