Sunday, December 8, 2013

Create a simple custom HTTPServer with Python

The example demonstrate how to implement a simple HTTPServer using Python, with custom HTML. The port number, 8080, is hard coded in py. You can visit it by enter <Raspberry Pi IP>:8080 in your browser. To end the server, press Ctrl-C.

a simple custom HTTPServer with Python
a simple custom HTTPServer with Python
Enter the code:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

class myHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write(
            "Hello from <b>Raspberry Pi</b> running <b><i>Python</i></b>")
        self.wfile.write(
            "<a href='http://helloraspberrypi.blogspot.com'>Hello Raspberry Pi</>")
        return

try:
    server = HTTPServer(('', 8080), myHandler)
    print 'HTTPServer started'
    server.serve_forever()

except KeyboardInterrupt:
    print 'server.socket.close()'
    server.socket.close()



You can run it in IDLE, or direct run it in command line:
$ python myPythonHttpServer.py

No comments: