changeset 1:eb2cb7ebc849

moving to a handler architecture
author k0s <k0scist@gmail.com>
date Thu, 29 Oct 2009 15:08:54 -0400
parents 72cb6dc31e3f
children 4ebaf68f2272
files webob_view/template/+package+/+package+.py_tmpl webob_view/template/+package+/factory.py_tmpl webob_view/template/+package+/handlers.py
diffstat 3 files changed, 58 insertions(+), 32 deletions(-) [+]
line wrap: on
line diff
--- a/webob_view/template/+package+/+package+.py_tmpl	Tue Oct 27 15:04:33 2009 -0400
+++ b/webob_view/template/+package+/+package+.py_tmpl	Thu Oct 29 15:08:54 2009 -0400
@@ -2,9 +2,10 @@
 ${repr(project)}: a view with webob
 """
 
-from webob import Request, Response, exc
+from handlers import Get, Post
+from webob import Request, exc
 
-class View(object):
+class Dispatcher(object):
 
     ### class level variables
     defaults = {}
@@ -12,36 +13,14 @@
     def __init__(self, **kw):
         for key in self.defaults:
             setattr(self, key, kw.get(key, self.defaults[key]))
-        self.response_functions = { 'GET': self.get,
-                                    'POST': self.post,
-                                    }
+        self.handlers = [ Get, Post ]
 
     ### methods dealing with HTTP
     def __call__(self, environ, start_response):
         request = Request(environ)
-        res = self.make_response(request)
+        for h in self.handlers:
+            if h.match(request):
+                handler = h(request)
+                break
+        res = handler()
         return res(environ, start_response)
-                                
-    def make_response(self, request):
-        return self.response_functions.get(request.method, self.error)(request)
-
-    def get_response(self, text, content_type='text/html'):
-        res = Response(content_type=content_type, body=text)
-        return res
-
-    def get(self, request):
-        """
-        return response to a GET requst
-        """
-        return self.get_response('Hello, world')
-
-    def post(self, request):
-        """
-        return response to a POST request
-        """
-        return exc.HTTPOk("Ok")
-
-    def error(self, request):
-        """deal with non-supported methods"""
-        return exc.HTTPMethodNotAllowed("Only %r operations are allowed" % self.response_functions.keys())
-        
--- a/webob_view/template/+package+/factory.py_tmpl	Tue Oct 27 15:04:33 2009 -0400
+++ b/webob_view/template/+package+/factory.py_tmpl	Thu Oct 29 15:08:54 2009 -0400
@@ -1,4 +1,4 @@
-from ${package} import View
+from dispatcher import Dispatcher
 from paste.httpexceptions import HTTPExceptionHandler
 
 def factory(global_conf, **app_conf):
@@ -7,6 +7,6 @@
     args = dict([(key.split(keystr, 1)[-1], value)
                  for key, value in app_conf.items()
                  if key.startswith(keystr) ])
-    app = View(**args)
+    app = Dispatcher(**args)
     return HTTPExceptionHandler(app)
     
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/webob_view/template/+package+/handlers.py	Thu Oct 29 15:08:54 2009 -0400
@@ -0,0 +1,47 @@
+from cgi import escape
+from urlparse import urlparse
+from webob import Response, exc
+
+class Handler(object):
+    def __init__(self, request):
+        self.request = request
+        self.application_path = urlparse(request.application_url)[2]
+
+    def link(self, path=(), permanant=False):
+        if isinstance(path, basestring):
+            path = [ path ]
+        path = [ i.strip('/') for i in path ]
+        if permanant:
+            application_url = [ self.request.application_url ]
+        else:
+            application_url = [ self.application_path ]
+        path = application_url + path
+        return '/'.join(path)
+
+    def redirect(self, location):
+        raise exc.HTTPSeeOther(location=location)
+
+class Get(Handler):
+
+    @classmethod
+    def match(cls, request):
+        return request.method == 'GET'
+
+    def __call__(self):
+        name = self.request.GET.get('name', 'world')
+        retval = """<html><body><form method="post">Hello,
+<input type="text" value="name"/></form></body></html>""" 
+        return Response(content_type='text/html', 
+                        body=retval % name)
+
+class Post(Handler):
+
+    @classmethod
+    def match(cls, request):
+        return request.method == 'POST'
+
+    def __call__(self):
+        name = 'foo' # XXX get from self.request.POST
+        name = escape(name)
+        self.redirect(self.link('/?name=%s' % name))
+