Pythoni http serveriteegi kasutamine

Allikas: Lambda
#!/usr/bin/env python3


# ======= imports =======

import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import unquote

# ======= configuration globals ======

host_name="localhost"
server_port=8080
logfile="httplog" # here server logs the requests
#logfile="/dev/null" 

# === request processing ===

class MyServer(BaseHTTPRequestHandler):
  def do_GET(self):
    text=unquote(self.path) # urldecode 
    result=text # to make the server do smth useful, modify here
    self.send_response(200)
    self.send_header("Content-type", "text/plain")
    self.end_headers()    
    self.wfile.write(bytes("%s\n" % result, "utf-8"))


# ====== starting ======

if __name__ == "__main__":   
  print("Server started http://%s:%s" % (host_name, server_port))
  webServer = HTTPServer((host_name, server_port), MyServer)
  try:
    buffer = 1
    sys.stderr = open(logfile, 'w', buffer)
    webServer.serve_forever()
  except KeyboardInterrupt:
    pass

  
  webServer.server_close()
  print("Server stopped.")

# ===== the end ======