Python comes with a set of servers (from low to high level): socket –> socketserver –> HTTPServer.
Socket is the low-level networking interface. Basic steps on the server-side:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP/IP, create socket s.bind(('127.0.0.1', 8080)) s.listen(5) while True: conn, addr = s.accept() data = conn.recv() #processing conn.send(response) conn.close()
Socketserver simplifies this process by wrapping all socket creation, bind, listen, accept into creating a socketserver instance, and use a requestHandler for all processing.
class myTCPHandler(socketserver.BaseRequestHandler): def handle(self): #must override this function data = self.request.recv() #self.request is a socket object for stream services #processing self.request.send() s = socketserver.TCPServer((HOST, PORT), myTCPHandler) s.serve_forever()
All the above are very easy to write and extremely flexible, but also easy to get messy. HTTP Server , especially used with CGIHTTPRequestHandler, help organize code nicely and still allow dynamic content generation. (CGIHTTPRequestHandler mirrors exactly SimpleHTTPRequestHandler in serving static local directory therefore I’ll skip SimpleHTTPRequestHandler).
The simplest cgi server has three parts:
1. main program
handler = http.server.CGIHTTPRequestHandler httpd = http.server.HTTPServer((HOST, PORT), handler) #HTTPServer is actually TCPServer but storing server_name and server_port, which CGIHTTPRequestHandler requires. httpd.serve_forever()
2. your index.html page, in which you specify the cgi script (cgi-bin/*.py) in form’s action attribute.
3. cgi script, placed in cgi-bin/ directory. Several quick points on syntax:
3.1 first line is the python executable path:
3.2 get form data through:
form = cgi.FieldStorage(). This is a dictionary-like object where you access values using
3.3 Python executes all cgi scripts as ‘others’, so make sure permission is granted properly:
chmod 0755 scriptName
3.4 cgi builds response through standard output (
cgi allows nice de-coupling of codes and is in someway very much like a mini-django, but much less daunting and in my mind better (or more flexible) for personal small projects.