I'm dabbling with Python and HTTP. Have created this simple server script I run with python cli.py serve. The server starts and works, but the keyboard interrupt Ctrl+C only gets trough on the next page refresh, not when I actually press Ctrl+C in the terminal.. Any fix for this? Note: works immediately when no request have come in yet.
from http.server import HTTPServer, BaseHTTPRequestHandler
import sys, signal
commands = ["serve"]
class Server(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/":
self.path = "/index.html"
self.send_response(200)
self.end_headers()
self.wfile.write(bytes("Tere, maailm!!",'utf-8'))
if len(sys.argv) > 1 and sys.argv[1] in commands:
index = commands.index(sys.argv[1])
if index == 0: # serve command
print("Starting web server. Press Ctrl+C to exit!")
httpd = HTTPServer(("localhost", 8080), Server)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Shutting down...")
httpd.socket.close()
sys.exit(0)
else:
print("Usage: python tab.py [command], where [command] is any of", commands)
Same problem... I discovered ThreadingHTTPServer, that works (instead of HTTPServer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With