Created
October 9, 2014 10:20
-
-
Save mildred/67d22d7289ae8f16cae7 to your computer and use it in GitHub Desktop.
Python 3 http.server with PUT support
This file contains 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") | |
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) |
How to test this code?
How to test this code?
default bind doesn't work for me... try replacing default=''
with default='0.0.0.0'
or you could spell it out python3 serv.py --bind=0.0.0.0 8000
Thanks for sharing this!
The code mostly worked for me but I used to get Error: socket hang up
until I added self.end_headers()
after the self.send_response
on line 21. Then it worked like a charm.
It might be worth mentioning that I'm running this in a docker container.
Works just fine with the fixes by @lberenguer and @rayfoss . Thanks!
how do you read the payload of the put request? I have a client sending a put request with some payload data but i dont see a method to parse the payload in python
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks a lot for the source code!
I had to add self.end_headers() after self.send_response(201, "Created") for my client to receive the 201 http code.