-
-
Save jongiddy/b26ce43d9da8eb5e9174f4971a80fd9b to your computer and use it in GitHub Desktop.
Python 3 http.server with PUT support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
import http.server | |
import os | |
class HTTPRequestHandler(http.server.SimpleHTTPRequestHandler): | |
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: | |
try: | |
os.makedirs(os.path.dirname(path)) | |
except FileExistsError: pass | |
length = int(self.headers['Content-Length']) | |
with open(path, 'wb') as f: | |
f.write(self.rfile.read(length)) | |
self.send_response(201, "Created") | |
self.end_headers() | |
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() | |
http.server.test(HandlerClass=HTTPRequestHandler, port=args.port, bind=args.bind) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment