#!/usr/bin/env python
# cgistate_hiddenfields.py -- Preserving CGI state with HTML hidden fields

import cgitb; cgitb.enable()
import cgi
import sys, os

FORMTEXT_TMPL  = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>CGI Counter 2</title>
  </head>
  <body>
    <p>Current counter value: %(value)s</p>
    <form action="%(action)s" method="POST">
      <input type="hidden" name="state" value="%(value)s" />
      <input type="submit" value="Increment counter"/>
    </form>
  </body>
</html>'''

def state_fetch(form):
    try:
        state = int(form['state'].value)
    except:
        state = 1
    finally:
        return state

def state_update(state):
    state = state + 1
    return state

def state_store(state):
    if 'SCRIPT_NAME' not in os.environ:
        return "This is not a CGI script. Can't call again."
    else:
        return FORMTEXT_TMPL % \
               { 'action': os.environ.get('SCRIPT_NAME', 'not_a_cgi'),
                 'value' : str(state) }

print "Content-type: text/html"
print

result = []

form = cgi.FieldStorage()
if 'state'  not in form:
    print FORMTEXT_TMPL % \
          { 'action': os.environ.get('SCRIPT_NAME', 'not_a_cgi' ),
            'value':  '1' }
    sys.exit(0)

# Fetch old counter value from client
oldstate = state_fetch(form)

# Compute new counter value
newstate = state_update(oldstate)

# Send new counter value to client
result.append(state_store(newstate))
print '\n'.join(result)
