Added logging and Request classes.
authorEugen Sawin <sawine@me73.com>
Sun, 11 Dec 2011 02:27:29 +0100
changeset 10ab694dc54515
parent 9 44d912089ce1
child 11 4d3f6e49e8fc
Added logging and Request classes.
client/machine.html
client/scripts/client.js
server/server.py
     1.1 --- a/client/machine.html	Sat Oct 08 01:05:50 2011 +0200
     1.2 +++ b/client/machine.html	Sun Dec 11 02:27:29 2011 +0100
     1.3 @@ -20,8 +20,7 @@
     1.4        </p>
     1.5      </view-right>
     1.6    </view-area>
     1.7 -  <autocompletion-area>
     1.8 -    
     1.9 +  <autocompletion-area>    
    1.10    </autocompletion-area>
    1.11    <command-area>
    1.12      <form name="com-form">
     2.1 --- a/client/scripts/client.js	Sat Oct 08 01:05:50 2011 +0200
     2.2 +++ b/client/scripts/client.js	Sun Dec 11 02:27:29 2011 +0100
     2.3 @@ -1,9 +1,8 @@
     2.4  //--allow-file-access-from-files
     2.5 -var server = "http://127.0.0.1:8080";
     2.6 +var server = "http://localhosts:8080";
     2.7  var view_left = "<view-left><h2>Machine</h2><p>Be yourself within Machine.</p></view-left>";
     2.8  
     2.9 -function command()
    2.10 -{
    2.11 +function command() {
    2.12      var com = document.getElementById("com");
    2.13      $.ajax({url: server + "/com",
    2.14  	    data: com.value,
    2.15 @@ -12,26 +11,20 @@
    2.16      com.value = ""; 
    2.17  }
    2.18  
    2.19 -function callback(data, status, xhr)
    2.20 -{
    2.21 +function callback(data, status, xhr) {
    2.22      view_left = "<view-left><h2>Machine</h2><p>" + data.time + "</p></view-left>";
    2.23      $("view-left").replaceWith(view_left);   
    2.24  }
    2.25  
    2.26 -$(document).ready
    2.27 -(
    2.28 -    function()
    2.29 -    {
    2.30 +$(document).ready (
    2.31 +    function() {
    2.32  	$("view-left").replaceWith(view_left);
    2.33      }
    2.34  );
    2.35  
    2.36 -$(document).keypress
    2.37 -(
    2.38 -    function(event) 
    2.39 -    {
    2.40 -	if (event.which == 13) 
    2.41 -	{
    2.42 +$(document).keypress (
    2.43 +    function(event) {
    2.44 +	if (event.which == 13) {
    2.45  	    event.preventDefault();
    2.46  	    command();
    2.47  	}
     3.1 --- a/server/server.py	Sat Oct 08 01:05:50 2011 +0200
     3.2 +++ b/server/server.py	Sun Dec 11 02:27:29 2011 +0100
     3.3 @@ -1,36 +1,49 @@
     3.4 -#!/usr/bin/python
     3.5 +#! /usr/bin/env python3
     3.6 +"""
     3.7 +Name: Machine Server
     3.8 +Author: Eugen Sawin <sawine@me73.com>
     3.9 +"""
    3.10  
    3.11  from argparse import ArgumentParser
    3.12 +from http.server import BaseHTTPRequestHandler, HTTPServer
    3.13 +import socketserver
    3.14 +from urllib.parse import urlparse
    3.15 +import logging
    3.16 +
    3.17 +ENCODING = "utf-8"
    3.18 +
    3.19  
    3.20  def parse_args():
    3.21      parser = ArgumentParser(description="")
    3.22 -    parser.add_argument("port", type=int, help="port")
    3.23 -    parser.add_argument("-a", help="host address")
    3.24 +    parser.add_argument("-p", type=int, default=8080, help="port")
    3.25 +    parser.add_argument("-a", default="localhost", help="host address")
    3.26 +    parser.add_argument("-l", default="log/server.log", help="log file")
    3.27      return parser.parse_args()	
    3.28  
    3.29 +
    3.30  def main():
    3.31      args = parse_args()
    3.32 -    port = args.port
    3.33 -    server = Server("localhost", port, GetHandler)
    3.34 +    logging.basicConfig(filename=args.l, level=logging.DEBUG,
    3.35 +                        format="[%(levelname)s @ %(asctime)s] %(message)s",
    3.36 +                        datefmt="%d.%m.%Y %I:%M:%S")
    3.37 +    server = Server(args.a, args.p, GetHandler)
    3.38      server.run()
    3.39  
    3.40 -from BaseHTTPServer import BaseHTTPRequestHandler
    3.41 -from BaseHTTPServer import HTTPServer
    3.42 -import SocketServer
    3.43 -import urlparse
    3.44  
    3.45  class GetHandler(BaseHTTPRequestHandler):
    3.46 +
    3.47      def do_GET(self):
    3.48 +        logging.debug("Received query: %s" % self.path)
    3.49 +        request = Request(self.path)
    3.50 +        logging.info("Request: %s" % request)
    3.51          if self.path == "/":
    3.52              self.path = "/machine.html"
    3.53 -
    3.54 -        parsed_path = urlparse.urlparse(self.path)
    3.55 -        message = '\n'.join(("client: %s:%i" % self.client_address,
    3.56 +        parsed_path = urlparse(self.path)
    3.57 +        message = "\n".join(("client: %s:%i" % self.client_address,
    3.58                               "path: %s" % parsed_path.path,
    3.59                               "query: %s" % parsed_path.query,
    3.60                               "params: %s" % parsed_path.params))
    3.61 -        self.send_response(200) 
    3.62 -       
    3.63 +        self.send_response(200)        
    3.64          resource = True
    3.65          if parsed_path.path.endswith(".html"):            
    3.66              self.send_header("Content-type", "text/html")          
    3.67 @@ -42,20 +55,50 @@
    3.68              self.send_header("Content-type", "application/json")  
    3.69              resource = False
    3.70          self.end_headers()
    3.71 +        if resource:
    3.72 +            self.wfile.write(bytes(open("../client" + parsed_path.path).read(), ENCODING))
    3.73 +        else:           
    3.74 +            self.wfile.write(bytes("{'time': 73}", ENCODING))
    3.75  
    3.76 -        if resource:
    3.77 -            self.wfile.write(open("../client" + parsed_path.path).read())
    3.78 -        else:           
    3.79 -            self.wfile.write("{\"time\": 73}")
    3.80  		
    3.81  class Server(HTTPServer):
    3.82 +
    3.83      def __init__(self, host, port, handler):
    3.84          HTTPServer.__init__(self, (host, port), handler)
    3.85          self.host = host
    3.86          self.port = port
    3.87 +
    3.88      def run(self):
    3.89 +        logging.info("Server ready and listening at port %i." % self.port)
    3.90          self.serve_forever()
    3.91  
    3.92 +class Request:
    3.93 +
    3.94 +    _request_types = {"help": []}
    3.95 +            
    3.96 +    def __init__(self, query):
    3.97 +        self.args = {}
    3.98 +        pos = query.find("?")
    3.99 +        if pos == -1:
   3.100 +            self.__class__ = WebRequest     
   3.101 +            self.args["doc"] = query
   3.102 +        else:
   3.103 +            com = query[:pos]
   3.104 +            arg_str = query[pos:]
   3.105 +            for t, args in _request_types:
   3.106 +                pass
   3.107 +
   3.108 +    def __str__(self):
   3.109 +        return "%s(%s)" % (str(self.__class__).partition(".")[-1].rstrip("'>"),
   3.110 +                           ", ".join(["%s: %s" % (k, str(v))
   3.111 +                                      for k, v in self.args.items()]))
   3.112 +
   3.113 +class WebRequest(Request):
   3.114 +
   3.115 +    def __call__(self):
   3.116 +        pass
   3.117 +
   3.118 +
   3.119  if __name__ == "__main__":
   3.120  	main()
   3.121