#
# Copyright(C) 2008 Litesim Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A nice simple httpd with REST services
# Should use mulib, but want to integrate easily with ipy for libsl goodness
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
def gen_plain_page(title,content=''):
return """
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>@TITLE</title>
</head>
<body>
<h1>@TITLE</h1>
<p>
@CONTENT
</p>
</body>
</html>
""".replace('@TITLE',title).replace('@CONTENT',content)
class litesim_http_resource:
def __init__(self):
self.content_type='text/html'
def handle_get(self,segments=[]):
return None
def handle_post(self,segments=[],body=None):
return None
class html_res(litesim_http_resource):
content = None
def handle_get(self,segments=[]):
return self.content
def gen_htmlres(content):
newclass = type('html_content',(html_res,),dict(content=content))
return newclass
def gen_plain_res(title,content):
return gen_htmlres(gen_plain_page(title,content))
default_res = gen_plain_res('Hello there!','You\'ve reached the default homepage')
404_res = gen_plain_res('404 - Not found','The resource you were looking for could not be found')
class litesim_http_handler(BaseHTTPRequestHandler):
def do_GET(self):
self.url_segments = self.path.split('/')
self.url_segments.remove('')
if (self.url_segments.__len__()==1) and self.url_segments[0]=='':
self.get_resource(default_res,[])
else:
self.get_resource(404_res,[])
def get_resource(self,res,segments,code=200):
res_obj = res()
response = res_obj.handle_get(segments)
if response == None:
self.get_resource(404_res,[])
else:
self.send_response(code)
self.send_header('Content-type',res_obj.content_type)
self.send_header('Content-length',str(len(response)))
self.end_headers()
self.wfile.write(response)
if __name__ == '__main__':
server = HTTPServer(('',8000),litesim_http_handler)
server.serve_forever()