Anonymous avatar Anonymous committed d540fc9

fix sprox

Comments (0)

Files changed (4)

basefw/pyconjp2011/framework/application.py

 from webob import Request, Response
 from webob.dec import wsgify
-from webob.exc import HTTPNotFound
+from webob.exc import HTTPNotFound, HTTPMethodNotAllowed
 from routes import Mapper
 
 class Application(object):
         if route.name not in self.apps:
             raise HTTPNotFound(location=request.url)
         app = self.apps[route.name]
+        request.application = self
         request.urlvars.update(matchdict)
         return app(request)
 
+    def route_url(self, route_name, **kw):
+        return self.mapper._routenames[route_name].generate(**kw)
+
+def rest_controller(cls):
+    def wraped(request):
+        obj = cls(request)
+        try:
+            method = getattr(obj, request.method.lower())
+        except AttributeError:
+            raise HTTPMethodNotAllowed
+        return method()
+    return wraped

sprox/pyconjp2011/sprox_demo/__init__.py

 from webob import Request, Response
 from webob.dec import wsgify
 from sqlalchemy import engine_from_config
-from sprox.formbase import AddRecordForm
+from sprox.formbase import AddRecordForm, EditableForm
+from sprox.tablebase import TableBase
+from sprox.fillerbase import TableFiller
 from mako.lookup import TemplateLookup
 import tw.forms
+from formencode import Invalid
 
+from ..framework.application import Application, rest_controller
 from .. import models
 
 here = os.path.dirname(__file__)
 
 class UserForm(AddRecordForm):
     __model__ = models.User
+    __require_fields__ = ['user_name']
+    __omit_fields__ = ['_password']
+
     user_image = tw.forms.FileField('user_image')
+    password = tw.forms.PasswordField('password', 
+                                      validator=tw.forms.validators.NotEmpty)
 
 user_form = UserForm(models.DBSession)
 
-@wsgify
+class EditUserForm(EditableForm):
+    __model__ = models.User
+    __require_fields__ = ['user_name']
+    __omit_fields__ = ['_password']
+
+    user_image = tw.forms.FileField('user_image')
+    password = tw.forms.PasswordField('password')
+
+edit_user_form = EditUserForm(models.DBSession)
+
+
+class UserTable(TableBase):
+    __model__ = models.User
+
+user_table = UserTable(models.DBSession)
+
+class UserTableFiller(TableFiller):
+    __model__ = models.User
+
+user_table_filler = UserTableFiller(models.DBSession)
+    
 def index(request):
     tmpl = templates.get_template('index.mak')
-    return Response(tmpl.render(form=user_form))
+    value = user_table_filler.get_value()
+    return Response(tmpl.render(form=user_table, value=value, request=request))
+
+class UserFormView(object):
+    def __init__(self, request):
+        self.request = request
+
+    def get(self):
+        tmpl = templates.get_template('index.mak')
+        return Response(tmpl.render(form=user_form, request=self.request))
+
+    def post(self):
+        try:
+            params = user_form.validate(self.request.params)
+            u = models.User(user_name=params['user_name'],
+                            password=params['password'])
+            models.DBSession.add(u)
+        except Invalid, e:
+            
+            tmpl = templates.get_template('index.mak')
+            return Response(tmpl.render(form=user_form, request=self.request))
+
+add_user_view = rest_controller(UserFormView)
+
+class EditUserFormView(object):
+    def __init__(self, request):
+        self.request = request
+
+    def get(self):
+        user = models.DBSession.query(models.User).filter_by(id=self.request.urlvars['user_id']).one()
+        tmpl = templates.get_template('index.mak')
+        return Response(tmpl.render(form=edit_user_form, request=self.request, 
+                                    value=user))
+    def post(self):
+        try:
+            params = edit_user_form.validate(self.request.params)
+            user = models.DBSession.query(models.User).filter_by(id=self.request.urlvars['user_id']).one()
+            user.user_name = params['user_name']
+            if params['password']:
+                user.password = params['password']
+            if params['groups']:
+                user.groups = models.DBSession.query(models.Group).filter(models.Group.id.in_(params['groups'])).all()
+            else:
+                user.groups = []
+            tmpl = templates.get_template('index.mak')
+            return Response(tmpl.render(form=edit_user_form, request=self.request, 
+                                        value=user))
+
+        except Invalid, e:
+            
+            tmpl = templates.get_template('index.mak')
+            return Response(tmpl.render(form=edit_user_form, request=self.request))
+
+edit_user_view = rest_controller(EditUserFormView)
 
 from tw.api import make_middleware
 
 def main(global_conf, **settings):
     engine = engine_from_config(settings)
     models.init_db(engine)
-    application = index
+    application = Application()
+
+    application.add_route('index', '/', index)
+    application.add_route('add_user_form', '/add_user', add_user_view)
+    application.add_route('edit_user_form', '/{user_id}/edit', edit_user_view)
+
     application = make_middleware(application, {
         'toscawidgets.framework.default_view': 'mako',
         'toscawidgets.middleware.inject_resources': True,

sprox/pyconjp2011/sprox_demo/templates/index.mak

 <title>Sprox Demo</title>
 </head>
 <body>
-${form()}
+${form(value)}
+<a href="${request.application.route_url('add_user_form')}">Add</a>
 </body>
 </html>
     "sprox",
     "mako",
     "pyconjp2011.models",
+    "pyconjp2011.framework",
 ]
 
 points = {
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.