Commits

Dan Boitnott committed 7daf116

Templates working

  • Participants
  • Parent commits 085a3ff

Comments (0)

Files changed (1)

 import mimetypes
 import shutil
 import urlparse
+import traceback
+import socket
+
+import pystache
 
 RESOURCES = "resources"
 STATIC = "static"
     except:
         return None
 
+class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
+    renderer = pystache.Renderer(search_dirs=[resourcePath(TEMPLATES)], missing_tags='strict')
 
-class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
     def do_GET(self):
         if self.path == '/':
-            self.send_error(404, "Not implemented yet")
-            return
+            (cmd, subPath) = ("index", '')
+        else:
+            (head, tail) = os.path.split(self.path.lstrip('/'))
+            if head == 'static':
+                self.sendStatic(tail)
+                return
 
-        (head, tail) = os.path.split(self.path.lstrip('/'))
-        if head == 'static':
-            self.sendStatic(tail)
-            return
-
-        (cmd, subPath) = (tail, '') if head == '' else (head, tail)
+            (cmd, subPath) = (tail, '') if head == '' else (head, tail)
 
         methodName = 'cmd_' + cmd
         if not hasattr(self, methodName):
-            self.send_error(404)
+            self.send_error(404, cmd + " not implemented")
             return
 
         method = getattr(self, methodName)
         parts = urlparse.urlsplit(subPath)
-        method(parts.path, urlparse.parse_qs(parts.query))
+
+        try:
+            method(parts.path, urlparse.parse_qs(parts.query))
+        except KeyboardInterrupt as ex:
+            raise ex
+        except:
+            self.send_error(500, traceback.format_exc())
 
     def sendStatic(self, filename):
         fp = openResource(STATIC, filename)
         if not fp:
-            self.send_error(404)
+            self.send_error(404, "no such file")
             return
 
         with fp:
             # Send bytes
             shutil.copyfileobj(fp, self.wfile)
 
+    def sendTemplate(self, templateName, contentType = "text/html", **args):
+        args["request"] = {
+            "server_name": socket.gethostname()
+        }
+
+        print args
+
+        content = self.renderer.render_name(templateName, args)
+        self.send_response(200)
+        self.send_header("Content-type", contentType)
+        self.send_header("Content-Length", str(len(content)))
+        self.end_headers()
+        self.wfile.write(content)
+
     def cmd_version(self, path, query):
         self.send_response(200)
         self.send_header("Content-type", 'text/plain')
         self.end_headers()
         self.wfile.write("1")
 
+    def cmd_index(self, path, query):
+        self.sendTemplate("index.html")
+
 if __name__ == '__main__':
     server = BaseHTTPServer.HTTPServer(('127.0.0.1', 8088), Handler)
     try: