Skip to content

Instantly share code, notes, and snippets.

@mildred
Created October 9, 2014 10:20
Show Gist options
  • Save mildred/67d22d7289ae8f16cae7 to your computer and use it in GitHub Desktop.
Save mildred/67d22d7289ae8f16cae7 to your computer and use it in GitHub Desktop.
Python 3 http.server with PUT support
#!/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)
@lberenguer
Copy link

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.

@getnsv
Copy link

getnsv commented Jun 12, 2019

How to test this code?

@FossPrime
Copy link

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

@ro-tex
Copy link

ro-tex commented Jan 19, 2021

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.

@bijoy26
Copy link

bijoy26 commented Jun 7, 2022

Works just fine with the fixes by @lberenguer and @rayfoss . Thanks!

@abhiramraik
Copy link

abhiramraik commented Aug 5, 2022

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