To create a HTTP server in Python, we can use the built-in http.server
module. Here's how to create a simple HTTP server that listens on port 8080:
main.py221 chars11 lines
This code creates an instance of SimpleHTTPRequestHandler
and starts a TCP server on port 8080. You can modify the Handler
class to customize the behavior of the server, such as parsing request headers or handling file uploads.
To upload a file to the server, we can create a POST request using the requests
module. Here's an example that uploads an image file named "test.png":
main.py240 chars11 lines
This code sends a POST request to the server at http://localhost:8080/upload and includes a file parameter named "file" with the contents of "test.png". You can modify the files
dictionary to upload different files or parameters.
To return a binary response from the server, we can modify the do_GET
or do_POST
method of the Handler
class. Here's an example that returns a PNG image:
main.py451 chars14 lines
This code defines a custom CustomHandler
class that overrides the do_GET
method to check if the request is for a PNG image. If it is, it sends a 200 OK response with the appropriate Content-type header and sends the contents of the image file in the response body. To use this custom handler, replace the Handler
class instantiation in the first code block with CustomHandler
.
Note that this is just an example and you should implement appropriate safety checks and security measures in your server code.
gistlibby LogSnag