How to run CGI "hello world" with python http.server
From the http.server
docs:
CGIHTTPRequestHandler
can be enabled in the command line by passing the--cgi
option:
$ python3 -m http.server --bind localhost --cgi 8000
Put your script into cgi_directories
:
This defaults to
['/cgi-bin', '/htbin']
and describes directories to treat as containing CGI scripts.
Open in the browser:
$ python -mwebbrowser http://localhost:8000/cgi-bin/hello.py
where hello.py
:
#!/usr/bin/env python3print("Content-Type: text/html\n")print("<!doctype html><title>Hello</title><h2>hello world</h2>")
I had to make it executable on POSIX: chmod +x cgi-bin/hello.py
.
I created a complete example for a friend. It is a complete demo you can run with 8 simple copy-paste ready lines of code. Enjoy.
echo -e "\n\n Usage: after running this script, visit http://localhost:8000/cgi-bin/hello \n\n"mkdir /tmp/cgi-bin/cat > /tmp/cgi-bin/hello <<EOF#!/bin/bashecho -e "Content-Type: text/plain\n\n"; date; echo; envEOFchmod +x /tmp/cgi-bin/hello(cd /tmp; python3 -m http.server --cgi 8000)
I did this some time ago for Python2.7
from BaseHTTPServer import BaseHTTPRequestHandlerclass GetHandler(BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): x = self.wfile.write self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() # <--- HTML starts here ---> x("<html>") # <--- HEAD starts here ---> x("<head>") x("<title>Title goes here!</title>") x("</head>") # <--- HEAD ends here ---> # <--- BODY starts here ---> x("<body>") x("<p>This is a test.</p>") x("</body>") # <--- BODY ends here ---> x("</html>") # <--- HTML ends here --->if __name__ == '__main__': from BaseHTTPServer import HTTPServer server = HTTPServer(('localhost', 777), GetHandler) print 'Starting server, use <Ctrl + F2> to stop' server.serve_forever()
So in Python 3 you just need to change imports
from http.server import BaseHTTPRequestHandlerclass GetHandler(BaseHTTPRequestHandler): def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() def do_GET(self): x = self.wfile.write self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() # <--- HTML starts here ---> x("<html>") # <--- HEAD starts here ---> x("<head>") x("<title>Title goes here!</title>") x("</head>") # <--- HEAD ends here ---> # <--- BODY starts here ---> x("<body>") x("<p>This is a test.</p>") x("</body>") # <--- BODY ends here ---> x("</html>") # <--- HTML ends here --->if __name__ == '__main__': from http.server import HTTPServer server = HTTPServer(('localhost', 777), GetHandler) print('Starting server, use <Ctrl + F2> to stop') server.serve_forever()