Fosbenner.net

WSGI Example 2

This script will generate an HTML document that shows a few environment variables passed to the script. 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 using environ'
   desc = 'This page is generated by Python!'

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

   a(st('body'))
   a('\t' + elem('h1', 'Info about the user:'))

   a('\t' + elem('p', 'Your IP address is: ' + environ['REMOTE_ADDR']))
   a('\t' + elem('p', 'Your browser is: ' + environ['HTTP_USER_AGENT']))
   if 'HTTP_REFERER' in environ:
      a('\t' + elem('p', 'To get to this page, you followed a link on: ' + environ['HTTP_REFERER']))   
   else:
      a('\t' + elem('p', elem('a','Click here to reload this page and see referer',
                                  'href="' + environ['REQUEST_SCHEME'] +
                                  '://' + environ['HTTP_HOST'] +
                                  environ['REQUEST_URI'] + '"')))

   a(et('body'))
   a(et('html'))

   # add newlines and calculate content length
   length = 0
   for i in xrange(len(out)):
      out[i] += '\n'
      length += len(out[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)