Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BaseHTTPRequestHandler hangs on self.rfile.read()

I implemented a python server using the BaseHTTPRequestHandler and it, often times, will hang while reading from the socket fileobject. It doesnt seem to matter how many bytes I read. I could read 30k bytes and it wont hang or I could read 7k bytes and it would hang. It is reading a Base64 string encoded image so i understand if it takes a second or two to read but it literally just hangs.

And then sometimes, when I press CTRL-C, it'll unhang and magically read everything. It's really bizarre. Any help will be appreciated. Thanks. Also, this is python2.7.

Code:

def do_POST(self):
    print self.rfile
    # Processing HTTP POST request data
    content_len = int(self.headers.getheader('content-length'))
    print 'Reading from HTTP header. Size: %s' % (content_len)

    # THIS IS WHERE IT HANGS 
    post_body_json = self.rfile.read(content_len)

    print 'Got it. Moving on, now.'
    post_body = json.loads(post_body_json)
    image_data = post_body.get('img_string_b64', 'No Image String')

    print 'Decoding image string.'
    # Processing image data
    image_name = 'image.jpg'
    decoded_str = base64.decodestring(image_data)
    self.write_image_to_system(decoded_str, image_name)

    print 'Getting text translation.'
    opencv_handler = OpenCVHandler()
    # Get translation from OpenCV then play text audio
    text_trans = opencv_handler.get_text_translation_from_image(image_name)
    opencv_handler.play_audio_translation_from_text(text_trans)

    # Responding to the POST requester.
    # text_trans = 'Translated'
    response = text_trans
    self.send_response(200)  # OK
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write(response)

    return
like image 377
Chuck Onwuzuruike Avatar asked Nov 07 '22 23:11

Chuck Onwuzuruike


1 Answers

I had the same issue with the call self.rfile.read(length), blocking for AJAX requests in POST. This was due to an earlier statement :

form = cgi.FieldStorage(
    fp=self.rfile,
    headers=self.headers,
    environ={'REQUEST_METHOD': 'POST'}
)

Once this is removed, it worked. I hope it helps.

like image 91
user3366258 Avatar answered Nov 15 '22 05:11

user3366258