HTTP Server
from http.server import HTTPServer, SimpleHTTPRequestHandler server = HTTPServer(("", 8000), SimpleHTTPRequestHandler) server.serve_forever()
The above code will create a simple server and serve it over the port 8000 at your localhost. SimpleHTTPRequestHandler provides the directory listing output
To view the output go to http://localhost:8000/
Same code one-liner
To view the output go to http://localhost:8000/
Same code one-liner
python -m http.server
If you want to provide your own HTTPRequestHandler (customize the output) you can subclass the BaseHTTPRequestHandler and override its do_GET method:
from http.server import HTTPServer, BaseHTTPRequestHandler class MyHTTPHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header('Content-type','text/html') self.end_headers() f = self.wfile f.write(b"Hello World") return server = HTTPServer(("", 8000), MyHTTPHandler) server.serve_forever()
Instant servers like the one we looked at right now are frequently used to build quick status pages to monitor server health and other applications running on the same server. Let's modify our do_GET method to provide such page.
On my localhost I also have another java application running at port 5000, and this is a URL that tells me wether the application is alive or not: http://127.0.0.1:5000/data. I expect a positive response from the page:
from http.server import HTTPServer, BaseHTTPRequestHandler from urllib.request import urlopen class MyHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() try: app = urlopen("http://127.0.0.1:5000/data") if(app.getcode() == 200): self.wfile.write(b"Port 5100: SUCCESS") else: self.wfile.write(b"Port 5100: ERROR") except: self.wfile.write(b"Port 5100: FAIL") return server = HTTPServer(("", 8000), MyHTTPRequestHandler) server.serve_forever()
In the code above we are using the urlopen that we are already familiar with to access the page we are monitoring and read the HTTP status code, we then output success of failure based on the status we receive. It may also happen that the page will not even exist when the application is down, therefore we have the exception handler which, when exception occurs will output a failure message