Skip to content

Instantly share code, notes, and snippets.

@bwangelme
Last active June 23, 2018 14:04
Show Gist options
  • Save bwangelme/09c5af16081015d10753da2978d8be67 to your computer and use it in GitHub Desktop.
Save bwangelme/09c5af16081015d10753da2978d8be67 to your computer and use it in GitHub Desktop.
Python Hello,World Web Server
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from http.server import HTTPServer
from http.server import BaseHTTPRequestHandler
from http import HTTPStatus
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(HTTPStatus.OK)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b'Hello, Python!')
return
def run(server_class=HTTPServer, handler_class=MyHandler):
server_address = ('localhost', 8000)
httpd = server_class(server_address, handler_class)
try:
print("Server works on http://localhost:8000")
httpd.serve_forever()
except KeyboardInterrupt:
print("Stop the server on http://localhost:8000")
httpd.socket.close()
if __name__ == '__main__':
run()
@bwangelme
Copy link
Author

bwangelme commented Sep 17, 2016

BaseHTTPRequestHandler中关于响应的说明如下:

This server parses the request and the headers, and then calls a
function specific to the request type (). Specifically,
a request SPAM will be handled by a method do_SPAM(). If no
such method exists the server sends an error response to the
client. If it exists, it is called with no arguments: do_SPAM()
Note that the request name is case sensitive (i.e. SPAM and spam are different requests).

The various request details are stored in instance variables:

  • client_address is the client IP address in the form (host,port);
  • command, path and version are the broken-down request line;
  • headers is an instance of email.message.Message (or a derived class) containing the header information;
  • rfile is a file object open for reading positioned at the start of the optional input data part;
  • wfile is a file object open for writing.

IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!
The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form

Content-type: <type>/<subtype>
# where <type> and <subtype> should be registered MIME types, e.g. "text/html" or "text/plain".

@SirSerje
Copy link

Looks pretty simple 👍

@yvcode
Copy link

yvcode commented May 30, 2018

Thanks! that helped me understand localhost pretty well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment