Source

pyconjp2011 / formalchemy / pyconjp2011 / formalchemy_demo / __init__.py

import os
from webob import Request, Response
from webob.exc import HTTPFound
from sqlalchemy import engine_from_config
from mako.lookup import TemplateLookup
from formalchemy import FieldSet
from formalchemy import Field
from formalchemy import fields
from formalchemy import Grid

from .. import models
from ..framework.application import Application, rest_controller

here = os.path.dirname(__file__)
templates_dir = os.path.join(here, "templates")

templates = TemplateLookup(directories=[templates_dir])

class UserForm(FieldSet):
    def __init__(self, **kw):
        super(UserForm, self).__init__(model=models.User, **kw)
        self.user_name.required()
        self.add(Field('password').password().required())
        self.configure(exclude=[self._password])

user_form = UserForm(session=models.DBSession)
#user_form.append(Field(name='user_image').with_renderer(fields.FileFieldRenderer))

user_grid = Grid(models.User, session=models.DBSession)
user_grid.configure(readonly=True, exclude=[user_grid._password])

def index(request):
    users = models.DBSession.query(models.User).all()
    grid = user_grid.bind(users)
    tmpl = templates.get_template('index.mak')
    return Response(tmpl.render(form=grid, request=request))

class UserFormView(object):
    def __init__(self, request):
        self.request = request

    def get(self):
        tmpl = templates.get_template('add_user.mak')
        return Response(tmpl.render(form=user_form, request=self.request))

    def post(self):
        user = models.User()
        form = user_form.bind(user, data=self.request.params, session=models.DBSession)

        if form.validate():
            form.sync()
            form.model.password = form.password.value
            models.DBSession.add(form.model)
            raise HTTPFound(location=self.request.application.route_url('index'))
        tmpl = templates.get_template('add_user.mak')
        return Response(tmpl.render(form=form, request=self.request))

add_user_form = rest_controller(UserFormView)

def main(global_conf, **settings):
    engine = engine_from_config(settings)
    models.init_db(engine)
    application = Application()
    application.add_route('index', '/', index)
    application.add_route('add_user', '/add_user', add_user_form)

    return application