Skip to content

Instantly share code, notes, and snippets.

@joao-timescale
Created October 18, 2018 17:33
Show Gist options
  • Save joao-timescale/e3fd9922582984d3bde3b83915402db0 to your computer and use it in GitHub Desktop.
Save joao-timescale/e3fd9922582984d3bde3b83915402db0 to your computer and use it in GitHub Desktop.
Python3 HTTP server with PUT support
#!/usr/bin/env python
import argparse
import http.server
import sys
import socketserver
import os
class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self,req, client_addr, server):
http.server.SimpleHTTPRequestHandler.__init__(self, req, client_addr, server)
def do_GET(self):
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
# Send the html message
self.wfile.write(bytes("Hello World !", encoding="utf-8"))
self.wfile.flush()
return
def do_PUT(self):
path = self.translate_path(self.path)
if path.endswith('/'):
self.send_response(405, "Method Not Allowed")
self.wfile.write("PUT not allowed on a directory\n".encode())
return
else:
print(self.headers)
if 'Content-Length' in self.headers:
length = int(self.headers['Content-Length'])
print(f"length = {length}")
content = self.rfile.read(length)
print(f"content = {content}")
response = bytes(str(content), "utf-8")
self.send_response(201)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(response)))
self.send_header("Content-type", "application/json")
self.end_headers()
self.wfile.write(response) #send response
self.wfile.flush()
print(f"Response = {response}")
else:
content = "No Content-Length header!"
response = bytes(content, "utf-8")
self.send_response(201)
self.send_header("Access-Control-Allow-Origin","*")
self.send_header("Content-Length", str(len(response)))
self.send_header("Content-type", "application/json; encoding=utf-8")
self.end_headers()
self.wfile.write(response) #send response
self.wfile.flush()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--bind', '-b', default='', metavar='ADDRESS',
help='Specify alternate bind address '
'[default: all interfaces]')
parser.add_argument('port', action='store',
default=8000, type=int,
nargs='?',
help='Specify alternate port [default: 8000]')
args = parser.parse_args()
try:
with socketserver.TCPServer(("", args.port), HTTPRequestHandler) as httpd:
print("serving at port", args.port)
httpd.serve_forever()
except KeyboardInterrupt:
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment