Python WSGI Server

created:

updated:

tags: python wsgi

How do we get from HTTP to Python?

  • NGINX -> Gunicorn -> Django -> Python
  • HTTP comes into NGINX, Django does routing, etc.
  • WSGI happens in-between Gunicorn and Django application.

WSGI Code Example

from service import Registry, RPC

Registry.initialize()

def application(environ, start_response):
    result = RPC(environ).get_result()
    status, headers, value = result.values()
    start_response(status, headers)
    return [value]

PEP 333(3): Web Server Gateway Interface

This specifies a proposed standard interface between web servers and Python web applications or frameworks, to promote web application portability across a variety of web servers.

Historical Context

  • In early days, we had static web servers that serves static files
    • A lot of HTML files stored in your hard drive, and when request comes in, it grabs the files and returns data to users
    • It’s fast and uses caches
  • However, it wasn’t possible to send/receive things like session or dynamic views
    • As a result, a “Common Gateway Interface” was created and it invokes a script for dynamic content
    • This is popular in PHP and Perl codebase
    • Simple: you can set environment variables as input
    • Simple: you can use stdout as output
    • Limitation when used on Python web application:
      • It restarts on every request (Python interpreter as well)
  • We wanted something fast, dynamic and Pythonic
    • We wouldn’t need to reboot Python every time, but only call the function multiple times
    • A separate Python application that we can pass requests and get response from it and send it to users
  • Django was the process that runs when the request comes in, just getting through it. During this, it goes through the whole framework such as views, routes, middleware, etc.
  • NGINX is in front of all of this. It’s not part of WSGI.
    • NGINX is a web server like Gunicorn but with additional functionality.
    • If someone sends a very large file, Gunicorn will block and do stuff. However, NGINX is good at offloading that task buffering the large file and quickly handing it off to Gunicorn.

Other Notes

  • WSGI is an API (Application Programming Interface)
  • It is recommended not to use raw WSGI. Instead, use a framework such as Django, Flask, etc.

References