Home » Django & REST Api » Writing first WSGI application and running it with uWSGI

Writing first WSGI application and running it with uWSGI

WSGI is the Web Server Gateway Interface. It is a specification that describes how a web server communicates with web applications, and how web applications can be chained together to process one request.

Install uWSGI with python

Since uWSGI is a C application it will need build-essential and python headers for functionality. We can install this on Ubuntu as,

$ apt-get install build-essential python-dev

Now, we can install uwsgi as below,

$ pip install uwsgi

Writing helloworld wsgi application

$ vim helloworld.py
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World"]

This helloworld.py is composed of a single Python function. It is called “application” as this is the default function that the uWSGI Python loader will search for (but we can customize it).

Start http server

Now start uWSGI to run an HTTP server/router passing requests to your WSGI application:

Use ifconfig command to know your machines IP address,

$ ifconfig

use the Ipaddress from above command and port as you want and run the server as,

$ uwsgi --http $SERVER_IP_ADDRESS:$SERVER_PORT --wsgi-file helloworld.py

This all steps can be mentioned in a single script as,

#one time installations
/usr/bin/python3 -m pip install --upgrade pip
pip install uwsgi
apt-get install build-essential python-dev

uwsgi --http $SERVER_IP_ADDRESS:$SERVER_PORT --wsgi-file helloworld.py

echo "The server is now running on $SERVER_IP_ADDRESS:$SERVER_PORT"

Reference – https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html#installing-uwsgi-with-python-support

Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

Leave a Comment