How can I implement a simple web server using Python without using any libraries?
You should look at the SimpleHttpServer (py3: http.server) module.
Depending on what you're trying to do, you can either just use it, or check out the module's source (py2, py3) for ideas.
If you want to get more low-level, SimpleHttpServer extends BaseHttpServer (source) to make it just work.
If you want to get even more low-level, take a look at SocketServer (source: py2, py3).
People will often run python like python -m SimpleHttpServer
(or python3 -m http.server
) if they just want to share a directory: it's a fully functional and... simple server.
You can use socket programming for this purpose. The following snippet creates a tcp socket and listens on port 9000 for http requests:
from socket import *
def createServer():
serversocket = socket(AF_INET, SOCK_STREAM)
serversocket.bind(('localhost',9000))
serversocket.listen(5)
while(1):
(clientsocket, address) = serversocket.accept()
clientsocket.send("HTTP/1.1 200 OK\n"
+"Content-Type: text/html\n"
+"\n" # Important!
+"<html><body>Hello World</body></html>\n")
clientsocket.shutdown(SHUT_WR)
clientsocket.close()
serversocket.close()
createServer()
Start the server, $ python server.py
.
Open http://localhost:9000/
in your web-browser (which acts as client). Then in the browser window, you can see the text "Hello World" (http response).
EDIT** The previous code was only tested on chrome, and as you guys suggested about other browsers, the code was modified as:
- To make the response http-alike you can send in plain header with http version 1.1, status code 200 OK and content-type text/html.
- The client socket needs to be closed once response is submitted as it's a TCP socket.
- To properly close the client socket,
shutdown()
needs to be called socket.shutdown vs socket.close
Then the code was tested on chrome, firefox (http://localhost:9000/) and simple curl in terminal (curl http://localhost:9000).