Last active
May 31, 2024 10:18
-
-
Save fabiand/5628006 to your computer and use it in GitHub Desktop.
A simple HTTP Server supporting put (python3)
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
# python3 -m SimpleHTTPPutServer 8080 | |
from http.server import HTTPServer, SimpleHTTPRequestHandler | |
class PutHTTPRequestHandler(SimpleHTTPRequestHandler): | |
def do_PUT(self): | |
print(self.headers) | |
length = int(self.headers["Content-Length"]) | |
path = self.translate_path(self.path) | |
with open(path, "wb") as dst: | |
dst.write(self.rfile.read(length)) | |
self.send_response(200) | |
self.end_headers() | |
def run(server_class=HTTPServer, handler_class=PutHTTPRequestHandler): | |
server_address = ('', 8000) | |
httpd = server_class(server_address, handler_class) | |
httpd.serve_forever() | |
if __name__ == '__main__': | |
run() |
I've updated the gist to stay minimal, but be python3 based.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I made a few changes to @orgads' implementation --- thank you! --- that suit my needs. The GET method didn't work, because the file content was already binary while
_send_response
expected the message to be still a string. If you want to read it binary for optimal efficiency, just edit_send_response
instead.Also, I used it in a web-browser, where multiple files where being retrieved. It made me wait for 2 minutes before axios fetched it and I never saw it in the log. This is because the non-threaded version of the previous authors will simply not see the request coming in and ignore it, until axios tries another time (apparently, that is after 2 minutes). I solved it by using a threaded server from the same
http.server
library.The disclaimer still holds:
I recommend looking at the script --- it's not hard. But for those who don't have the time, the directory being served is expected to be the current working directory of the script (
cwd = os.path.normcase(os.getcwd())
), so either move to the directory and execute the script from there, or configure it so you can pass a parameter and share your updated version here ;-) I did the former with one of my scripts ("serve": "cd data; python3 ./server.py 8756"
)