Skip to content

Instantly share code, notes, and snippets.

@2matzzz
Created November 27, 2023 07:11
Show Gist options
  • Save 2matzzz/57be6d7e866b84c63559f022c6ff9e61 to your computer and use it in GitHub Desktop.
Save 2matzzz/57be6d7e866b84c63559f022c6ff9e61 to your computer and use it in GitHub Desktop.
python3 http post server
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import sys
from urllib.parse import unquote
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
file_name = os.path.basename(unquote(self.path))
if file_name:
content_length = self.headers.get('Content-Length')
if content_length:
content_length = int(content_length)
file_data = self.rfile.read(content_length)
save_path = os.path.join(os.getcwd(), file_name)
with open(save_path, "wb") as output_file:
output_file.write(file_data)
self.send_response(200)
self.end_headers()
self.wfile.write(b'File uploaded successfully.')
else:
self.send_response(411)
self.end_headers()
self.wfile.write(b'Content-Length header is missing.')
else:
self.send_response(400)
self.end_headers()
self.wfile.write(b'Invalid file name.')
if __name__ == '__main__':
if len(sys.argv) != 3:
print("Usage: python3 script.py <Host> <Port>")
sys.exit(1)
host, port = sys.argv[1], int(sys.argv[2])
httpd = HTTPServer((host, port), SimpleHTTPRequestHandler)
print(f"Starting httpd server on {host}:{port}")
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment