pythonpython-3.xapachemod-wsgiwsgi

Turn old Python web app into WSGI-ready and Apache


I have an ancient web application written in Python. It's basically a bunch of .py files. For instance:

display.py:

import cgi
import re
import string
import operator
from urllib.parse import urlparse
from errors import herigean
from routines import *

error = False

query = cgiFieldStorageToDict(cgi.FieldStorage())
opening_index = 0 # flag to indicate whether we're opening the index page
if ('what' not in query):
        query['what'] = 'index'
if 'fs' not in query:
        query['fs'] = str(default_font_size)

# open page to display
try:
        fil = open('html/'+query['what']+'.fmt')
        textlines = fil.read()
        queryreg = re.compile('QUERY:fs:QUERY')
      textlines = queryreg.sub(query['fs'],textlines)
        fil.close()
except IOError:
        error = True

if query['what'] == 'about':
        try:
                fil = open('legal/lgpl-3.0.txt')
                lgpl = fil.read()
                fil.close()
                fil = open('legal/gpl.txt')
                gpl = fil.read()
                fil.close()
                fil = open('html/availability.fmt')
                availability = fil.read()
                fil.close()
        except IOError:
                error = True
if query['what'] == 'corpus':
        try:
                fil = open('html/availability.fmt')
[...]
if error:
        herigean()
else:
        print(frontmatter)

etc.

How can I run this behind an Apache proxy, using mod_wsgi installed in my virtual environment? Right now I have a Pythong 3.11 virtual environment with mod_wsgi-express 5 installed in it.I can successfull run a test.py with:

mod_wsgi-express start-server test.py

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'Hello, world!']

How can I run my old Python application? Do I just wrap each .py file inside a def application(environ, start_response):? Any help will be highly appreciated.

Addition:

The application has an index.html within its www. Inside this, there's a <meta http-equiv="Refresh" content="0;url=display.py?what=index" />. That's how it's currently served.

Addition II

There's no way I can get an output: when using

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    [...]
    return print(frontmatter)

I get the whole HTML in the logs, follwed by TypeError: 'NoneType' object is not iterable and Internal Server Error on the browser.


Solution

  • Instead of print I should use yield bytes(html).