~talideon Running a Python WSGI application as a CGI script

Here on tilde.club, you can’t really run persistent applications. However, you can write pages with PHP and you can also write CGI scripts. If you want to run a dynamic site written with, say, Flask, your options are limited. However, CGI gives you a way of doing this without the need some kind of reverse proxy.

Python’s wsgiref module comes with a built-in CGI handler that can turn a WSGI application into a CGI script. Here’s a very simple example:

#!/usr/bin/env python3

from wsgiref.handlers import CGIHandler


def simple_app(environ, start_response):
    status = "200 OK"
    headers = [("Content-Type", "text/plain")]
    start_response(status, headers)
    return [b"Hello, world!"]


CGIHandler().run(simple_app)

Take that script, and drop it at ~/public_html/cgi-bin/test.cgi, ensuring that it’s executable. If you visit the equivalent address in your browser, you should see it print out a greeting.

In this example, you can replace simple_app in my example with your WSGI application object. Mind you, I haven’t tested this with anything complicated, so you might find issues with routes.

Copyright © Keith Gaughan, 2021