Skip to content

Instantly share code, notes, and snippets.

@caueb
Last active September 20, 2024 10:43
Show Gist options
  • Save caueb/3a9a122e3da3d6a8aa73c63da4ecf75f to your computer and use it in GitHub Desktop.
Save caueb/3a9a122e3da3d6a8aa73c63da4ecf75f to your computer and use it in GitHub Desktop.
Python webserver that supports PUT method to receive and save files.
#!/usr/bin/env python
"""Extend Python's built-in HTTP server to save files.
curl or wget can be used to send files with options similar to the following:
curl -X PUT --upload-file somefile.txt http://localhost:8000
wget -O- --method=PUT --body-file=somefile.txt http://localhost:8000/somefile.txt
__Note__: curl automatically appends the filename onto the end of the URL so
the path can be omitted.
"""
import os
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
class HTTPRequestHandler(SimpleHTTPRequestHandler):
"""Extend SimpleHTTPRequestHandler to handle PUT requests."""
def do_PUT(self):
"""Save a file following an HTTP PUT request."""
filename = os.path.basename(self.path)
# Don't overwrite files
if os.path.exists(filename):
self.send_response(409, 'Conflict')
self.end_headers()
reply_body = '"%s" already exists\n' % filename
self.wfile.write(reply_body.encode('utf-8'))
return
file_length = int(self.headers['Content-Length'])
with open(filename, 'wb') as output_file:
output_file.write(self.rfile.read(file_length))
self.send_response(201, 'Created')
self.end_headers()
reply_body = 'Saved "%s"\n' % filename
self.wfile.write(reply_body.encode('utf-8'))
def run(server_class=HTTPServer, handler_class=HTTPRequestHandler, port=8000):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f"Starting HTTP server on port {port}...")
httpd.serve_forever()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Simple HTTP Server with PUT support.')
parser.add_argument('--port', type=int, default=8000, help='Specify the port number (default: 8000)')
args = parser.parse_args()
run(port=args.port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment