我使用BaseHTTPRequestHandler实现了一个python服务器,它通常在从套接字文件对象读取时会挂起。我读多少字节似乎并不重要。我可以读取30k字节,但不会挂起,或者我可以读取7k字节,但会挂起。它正在读取Base64字符串编码的图像,因此我了解读取是否需要一两秒钟,但实际上只是挂起。
然后有时,当我按CTRL-C时,它将解开并神奇地读取所有内容。真的很奇怪任何帮助将不胜感激。谢谢。另外,这是python2.7。
代码:
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
我在POST中针对AJAX请求的调用self.rfile.read(length)遇到了相同的问题。这是由于先前的声明:
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
一旦删除,它就起作用了!希望对您有帮助...