Thursday 17 December 2015

Creating your own http server using python script.


This lesson is about creating your own web server without using apache. To do this we are using two libraries.
BaseHTTPServer and SimpleHTTPServer.  BaseHTTPServer creates the http daemon and SimpleHTTPServer
creates the http handler. The program takes one argument which is the port number to which server will be running.
If no port number is mentioned server will run on port 8000.







So here is the code for your Web Server.

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

Handler = SimpleHTTPRequestHandler
Server = BaseHTTPServer.HTTPServer

Protocol = "HTTP/1.1"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000

server_address = ("127.0.0.1", port)
# if you are opt to use this on your local machine 127.0.0.1, but you want to use it as web server in a network
# with various sub net then use 0.0.0.0 instead.

Handler.protocol_version = Protocol
httpd = Server(server_address, Handler)
print("HTTP Server started...")
httpd.serve_forever()

After saving this files (i.e. PythonWebServer.py), goto the command line and type
python PythonWebServer.py 8000 (8000 port number is optional.)

The directory where you executed PythonWebServer.py is the root directory of your web server.
Create a html file on the root, named say firstPage.html

Now open your browser and type localhost:8000/firstPage.html
And your html page will be parsed and displayed.

This type of web server can be used on your local desktop or small home network.

No comments: