Source

wsgitalk / examples5-forms / form_app.py

Full commit
'''
An example of using the third-party toscawidgets library to do form generation
and validation.

We define a form, then use it in a WSGI app. If the form validation succeeds,
we write the data out to a file. If it fails, we serve up the form again with
errors.

Interesting to note is that toscawidgets provides middleware that you have to
use in order for it work. Why? Since any widget has the ability to pull in
extra resources like images, Javascript, etc. (e.g. for the calendar date
picker) toscawidgets dynamically includes and serves up these resources for
the form pages. ToscaWidgets is a high level example of what can be done with
WSGI.
'''

import os.path

from framework import wsgiapp, dispatcher, template_response
from framework import null_handler, static_handler

import tw.forms as twf
from formencode.national import USPostalCode, USPhoneNumber
from formencode.api import Invalid as FormInvalid

DATA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')

## form #######################################################################

STATES = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI',
          'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN',
          'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH',
          'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA',
          'WV', 'WI', 'WY']

RegForm = twf.TableForm('reg_form', action='register', children=[
    twf.TextField('first_name', validator=twf.validators.NotEmpty),
    twf.TextField('last_name', validator=twf.validators.NotEmpty),
    twf.TextField('email', validator=twf.validators.All(twf.validators.Email, twf.validators.NotEmpty)),

    twf.TextField('address1', validator=twf.validators.NotEmpty),
    twf.TextField('address2'),
    twf.TextField('city', validator=twf.validators.NotEmpty),
    twf.SingleSelectField('state', options=['']+STATES, validator=twf.validators.NotEmpty),
    twf.TextField('zip', validator=twf.validators.All(USPostalCode(), twf.validators.NotEmpty)),

    twf.TextField('phone', validator=twf.validators.All(USPhoneNumber, twf.validators.NotEmpty)),
    twf.CalendarDatePicker('birth_date', validator=twf.validators.NotEmpty),
])

## app ########################################################################

@wsgiapp
def index(req):
    return template_response('index.html')

@wsgiapp
def reg_form(req):
    return template_response('reg_form.html', form=RegForm())

@wsgiapp
def register(req):
    try:
        form_data = RegForm.validate(req.POST)

        #form is valid, store it
        result = write_profile(**form_data)
        return template_response('thanks.html', result=result)
    except FormInvalid:
        #form is invalid
        return template_response('reg_form.html', form=RegForm(req.POST))

## profile ####################################################################

def write_profile(**kwargs):
    def mypprint(d):
        d = sorted(d.items(), key=lambda t: t[0])
        d = map(repr, d)
        d = "\n".join(d)
        return d
    from datetime import datetime
    from md5 import md5
    s = mypprint(kwargs)
    stamp = datetime.strftime(datetime.now(), "%Y%m%d%H%M")
    stamp += "_%s" % (md5(s).hexdigest())[:6]
    open(os.path.join(DATA_PATH, "%s.txt" % stamp), 'w').write(s)
    return s

## main #######################################################################

if __name__ == '__main__':
    hostname = 'localhost'
    port = 4000

    url_map = {
                '': index,
                'static': static_handler,
                'favicon.ico': null_handler,

                'reg_form': reg_form,
                'register': register,
              }

    from tw.api import make_middleware
    app = dispatcher(**url_map)
    app = make_middleware(app, stack_registry=True)

    from werkzeug import run_simple
    run_simple(hostname, port, app, use_debugger=True, use_reloader=True)