Fosbenner.net

WSGI Example 1

This script will generate an HTML document using WSGI. It is basically the same as CGI Example 1, but using WSGI instead of CGI. For context, see related article below.

#!/usr/bin/env python

def application(environ, start_response):
   """This function is called when accessing the webpage"""
   status = '200 OK'

   title = 'Example Site'
   desc = 'This page is generated by Python!'

   out = []
   out.append('<!DOCTYPE html>\n' + st('html') + '\n' +
      elem('head', '\n\t' +
      elem('title', title) + '\n\t' +
      eelem('meta', 'name="description" content="' + desc + '"') + '\n\t' +
      eelem('link', 'rel="stylesheet" href="https://fosbenner.net/s/playground.css"') + '\n'))

   out.append(elem('body', '\n\t' +
      elem('h1', 'This is a header') + '\n\t' +
      elem('p', 'This is a paragraph') + '\n\t' +
      elem('p', 'This is another paragraph') + '\n'
      ) + '\n' + et('html'))

   # calculate content length
   length = 0
   for i in out:
      length += len(i)

   response_headers = [('Content-type', 'text/html'),
                       ('Content-Length', str(length))]
   start_response(status, response_headers)

   return out

def st(tag, attr=""):
   """Generate HTML start tag"""
   if attr != "": #pad attr with a space
      attr = " " + attr
   return '<' + tag + attr + '>'

def et(tag):
   """Generate HTML end tag"""
   return '</' + tag + '>'

def elem(tag, content, attr=""):
   """Generate whole element"""
   return st(tag, attr) + content + et(tag)

def eelem(tag, attr=""):
   """Generate empty element"""
   attr += ' /' # add space, slash to end
   return st(tag, attr)