How can I implement a simple web server using Python without using any libraries?

I need to implement a very simple web server application in Python that will execute basic HTTP requests and responses and display very simple output on a web page. I'm not too worried that this is actually Python coding, but I'm not sure where to start? How to set it up? Single file? Multiple files? I probably have no idea how to approach the fact that this is a "server", so I am not familiar with how to access HTTP requests / sockets / processing requests, etc. Any tips? Resources?

+8
source share
4 answers

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 a client). Then in the browser window you can see the text "Hello World" (http-response).

EDIT ** The previous code was tested only on chrome, and as you guys suggested other browsers, the code was changed as:

  • To make the response http-the same, you can send a normal header with http version 1.1, a status code of 200 OK, and a text of type content / html.
  • The client socket should be closed after sending the response as a TCP socket.
  • To properly close the client socket, shutdown() must be called socket.shutdown vs socket.close

Then the code was tested on chrome, firefox ( http: // localhost: 9000 / ) and a simple curl in the terminal (curl http: // localhost: 9000 ).

+4
source

You should look at SimpleHttpServer (py3: http.server ).

Depending on what you are trying to do, you can just use it or check the source of the module ( py2 , py3 ) for ideas.

If you want a lower level, SimpleHttpServer extends BaseHttpServer ( source ) to make it just work.

If you want to get even lower level, look at SocketServer (source: py2 , py3 ).

People often run python, for example python -m SimpleHttpServer (or python3 -m http.server ) if they just want to split the directory: it is fully functional and ... a simple server.

+10
source

I decided to make this work in Python 3 and make it work on Chrome as an example for the online course that I am developing. Python 3, of course, needs encode() and decode() in the right places. Chrome - really wants to send its GET request before it receives data. I also added some error checking so that it clears its socket if you interrupt the server or it explodes:

 def createServer(): serversocket = socket(AF_INET, SOCK_STREAM) try : serversocket.bind(('localhost',9000)) serversocket.listen(5) while(1): (clientsocket, address) = serversocket.accept() rd = clientsocket.recv(5000).decode() pieces = rd.split("\n") if ( len(pieces) > 0 ) : print(pieces[0]) data = "HTTP/1.1 200 OK\r\n" data += "Content-Type: text/html; charset=utf-8\r\n" data += "\r\n" data += "<html><body>Hello World</body></html>\r\n\r\n" clientsocket.sendall(data.encode()) clientsocket.shutdown(SHUT_WR) except KeyboardInterrupt : print("\nShutting down...\n"); except Exception as exc : print("Error:\n"); print(exc) serversocket.close() print('Access http://localhost:9000') createServer() 

The server also prints an incoming HTTP request. The code, of course, sends only text / html regardless of the request - even if the browser requests an icon:

 $ python3 server.py Access http://localhost:9000 GET / HTTP/1.1 GET /favicon.ico HTTP/1.1 ^C Shutting down... 

But this is a pretty good example that basically shows why you want to use a framework like Flask or DJango, instead of writing your own. Thanks for the source code.

0
source

There is a very simple solution mentioned above, but the solution above does not work. This solution is tested on chrome and works. This is Python 3, although it can work on Python 2 since I never tested it.

 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(bytes("HTTP/1.1 200 OK\n" +"Content-Type: text/html\n" +"\n" # Important! +"<html><body>Hello World</body></html>\n",'utf-8')) clientsocket.shutdown(SHUT_WR) clientsocket.close() serversocket.close() createServer() 

This is better than the answer that was accepted, but I will post it so that future users can easily use it.

0
source

Source: https://habr.com/ru/post/912861/


All Articles