Sunday, December 18, 2011

Creating Web Page using Python including its Webserver (basehttpserver module)

It's possible to create web page using Python, even self hosted it using Python built in webserver (basehttpserver module)

Here the code. It'll create web server with port 8080 and if it's accessed, it'll show a page. In the code below, page showed for us is just plain text "magic content goes here". I am planning to investigate this self.wfile.write behavior.




from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        
        self.wfile.write("magic content goes here")

if __name__=="__main__":
    try:
        server = HTTPServer(("", 8080), Handler)
        server.serve_forever()
    except KeyboardInterrupt:
        server.socket.close()

Access with browser in address localhost:8080 or <whatever your ip address>:8080 and get this

From python