Python standard library comes with a in-built webserver which can be invoked for simple web client server communication. The port number can be assigned programmatically and the web server is accessed through this port. Though it is not a full featured web server which can parse many kinds of file, it can parse simple static html files and serve them by responding them with required response codes.
The below program starts a simple web server and opens it up at port 8001. The successful running of the server is indicated by the response code of 200 as shown in the program output.
import SimpleHTTPServer import SocketServer PORT = 8001 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()
When we run the above program, we get the following output −
serving at port 8001 127.0.0.1 - - [14/Jun/2018 08:34:22] "GET / HTTP/1.1" 200 -
If we decide to make the python server as a local host serving only the local host, then we can use the following programm to do that.
import sys import BaseHTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler HandlerClass = SimpleHTTPRequestHandler ServerClass = BaseHTTPServer.HTTPServer Protocol = "HTTP/1.0" if sys.argv[1:]: port = int(sys.argv[1]) else: port = 8000 server_address = ('127.0.0.1', port) HandlerClass.protocol_version = Protocol httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever()
When we run the above program, we get the following output −
Serving HTTP on 127.0.0.1 port 8000 ...