Last active
December 8, 2024 01:22
-
-
Save LucasParsy/3bc88bb7a7796cb0d5a218c11fa59829 to your computer and use it in GitHub Desktop.
python simple HTTP server with POST body logging
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 python3 | |
from http.server import HTTPServer, SimpleHTTPRequestHandler | |
from http import HTTPStatus | |
import sys | |
import string | |
import os | |
uploadPath = "/myupload/" | |
def format_filename(s): | |
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits) | |
filename = ''.join(c for c in s if c in valid_chars) | |
filename = filename.replace(' ','_') # I don't like spaces in filenames. | |
filename = "f_" + filename | |
return filename | |
class MyHandler(SimpleHTTPRequestHandler): | |
rbufsize = 0 | |
def do_POST(self): | |
self.send_response(HTTPStatus.OK) | |
self.end_headers() | |
mb = self.rfile.read(10000000) | |
if self.path.startswith(uploadPath): | |
fname = format_filename(self.path.split("/myupload/")[1]) | |
with open(fname, "wb") as f: | |
f.write(mb) | |
self.log_message("POST %s : wrote file %s", self.path, fname) | |
else: | |
self.log_message("POST %s : %s", self.path, mb) | |
port = 80 | |
ip = '0.0.0.0' | |
if len(sys.argv) >= 2 and sys.argv[1].isnumeric(): | |
port = int(sys.argv[1]) | |
print("serving on", ip, str(port), "folder ", os.getcwd()) | |
print(f"upload files on {uploadPath}/yourfilename.txt") | |
httpd = HTTPServer((ip, port), MyHandler) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment