Trying to build a simple python3 HTTP Server with http.server:
import http.server
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver
class Handler(BaseHTTPRequestHandler):
def do_PATCH(self):
print ("do_Patch called")
contentLength = int(self.headers['content-length'])
res = self.rfile.read(contentLength)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write('Something brilliant'.encode())
httpd = HTTPServer(("127.0.0.1",33181),Handler)
httpd.serve_forever()
Problem is that self.rfile.read() is blocking, so if I don't get the content-length exactly right I either get too little data or I hang.. Docs I've found says it's supposed to throw an exception in non-blocking mode but I've not found out how to set non-blocking mode.
I can get around this by setting the content-length as above, but I can also corrupt the content-length which hangs the thread:
import http.client
myValueableString = "Shorter than 300"
for mylen in [len(myValueableString), 300]:
conn = http.client.HTTPConnection("127.0.0.1",33181)
conn.request("PATCH","/test",myValueableString ,{'Content-length': mylen})
print(conn.getresponse().read().decode())
Is there any good way to 1) Force finding the "true" length of rfile stream, or 2) Force a timeout or 3) Enable "non-blocking" mode? I realize the code isn't recommended for production but this is the only real stumbling block I've encountered.