If you’re building web apps in Python, chances are you’ll encounter WSGI—the standard interface between web servers and Python web applications. And to serve your app in production, uWSGI is one of the most reliable, efficient, and scalable application servers available.
This tutorial will guide you through:
- Writing a minimal WSGI application
- Running it locally with uWSGI
- Understanding how it all works
🧱 What is WSGI?
WSGI (Web Server Gateway Interface) is a specification that allows a Python application to communicate with a web server. It acts as a bridge between your code and production servers like uWSGI, Gunicorn, or mod_wsgi.
✅ Think of it as the translator between your Python code and the server world.
🧑💻 Step 1: Write Your First WSGI App
Let’s write a minimal app.py
:
def application(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'text/plain')]
start_response(status, headers)
return [b"Hello, WSGI World!"]
📂 Save this as app.py
.
⚙️ Step 2: Install uWSGI
Make sure you have Python and pip installed. Then install uWSGI using:
pip install uwsgi
🔁 Use a virtual environment for better isolation.
🚀 Step 3: Run WSGI App with uWSGI
Use this simple command to serve your app:
uwsgi --http :8000 --wsgi-file app.py
🔍 What this does:
--http :8000
: Runs uWSGI with HTTP protocol on port 8000--wsgi-file app.py
: Points to your Python file with the WSGI application
🌐 Open your browser and go to:http://localhost:8000
You should see:
Hello, WSGI World!
🧠 Optional: Use uWSGI INI Configuration
Instead of a long command, you can use a config file app.ini
:
[uwsgi]
http = :8000
wsgi-file = app.py
master = true
processes = 2
threads = 2
Run it with:
uwsgi --ini app.ini
✅ More maintainable for production!
🛠️ Troubleshooting Tips
- Port already in use? Change
:8000
to another port, like:8080
. - Blank response? Ensure
application()
returns a list with byte strings. - Encoding error? Always return bytes, not strings (
b"Hello"
not"Hello"
).
📦 Bonus: Run WSGI App Behind Nginx (Production)
Later, for production, you can pair uWSGI with Nginx for better performance and scalability:
[uwsgi]
socket = 127.0.0.1:3031
wsgi-file = app.py
And configure Nginx to pass traffic to uWSGI using uwsgi_pass
.
🧠 Final Thoughts
WSGI and uWSGI are foundational technologies for Python web development. Learning how to write a basic WSGI app and run it with uWSGI prepares you for more advanced frameworks like Flask and Django—and gives you insight into what happens behind the scenes.
Did this guide help you launch your first WSGI app?
Leave a comment below and share your project or questions. Let’s build better Python backends together! 🐍🚀