LoginSignup
0
0

python script to set up a local server including put method

Last updated at Posted at 2024-02-21
# Import the http.server module
import http.server

# Define a custom handler class that inherits from SimpleHTTPRequestHandler
class PUTHandler(http.server.SimpleHTTPRequestHandler):
    # Override the do_PUT method to handle PUT requests
    def do_PUT(self):
        # Get the path of the request
        path = self.translate_path(self.path)
        # Try to open the file in write mode
        try:
            with open(path, "wb") as f:
                # Write the request body to the file
                f.write(self.rfile.read(int(self.headers["Content-Length"])))
                # Send a 200 OK response
                self.send_response(200)
                # End the headers
                self.end_headers()
        # If the file cannot be opened, send a 403 Forbidden response
        except OSError:
            self.send_error(403, "Forbidden")
            self.end_headers()

# Create a server object using the custom handler class
server = http.server.HTTPServer(("", 8080), PUTHandler)

# Start the server
server.serve_forever()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0