This article mainly introduces how to solve the thread crash error caused by the Python prompt [Errno32] Brokenpipe, which is a problem frequently encountered when ThreadingHTTPServer implements http services, for more information about how to solve the thread crash error caused by the Python prompt [Errno 32] Broken pipe, refer to the example in this article. Share it with you for your reference. The specific method is as follows:
1. Error
The http service implemented by ThreadingHTTPServer. if the client proactively disconnects the connection before the server returns, the server reports [Errno 32] Broken pipe error and causes the processing thread crash.
Next, let's take a look at an example. python version: 2.7
Sample code
The code is as follows:
#! /Usr/bin/env python #! Coding = UTF-8 import osimport timeimport socketimport threadingfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandlerfrom SocketServer import ThreadingMixIn class RequestHandler (BaseHTTPRequestHandler): def do_GET (self ): "processing get requests" query = self. path print "query: % s thread = % s" % (query, str (threading. current_thread () # ret_str =""+ Self. path +"
"+ Str (self. server) +"
"+ Str (self. responses) +""Ret_str =""+ Self. path +"
"+ Str (self. server) +""Time. sleep (5) try: self. send_response (200) self. send_header ('content-type', 'text/html ') self. end_headers () self. wfile. write (ret_str) into T socket. error, e: print "socket. error: Connection broke. aborting "+ str (e) self. wfile. _ sock. close () # close socket self. wfile. _ sock = None return False print "success prod query: % s" % (query) return True # multithreading class ThreadingHTTPServer (ThreadingMixIn, HTTPServer ): pass if _ name _ = '_ main _': serveraddr = ('', 9001) ser = ThreadingHTTPServer (serveraddr, RequestHandler) ser. serve_forever () sys. exit (0)
Running service
./Thread_http_server_error.py
1st times curl, waiting for return
The code is as follows:
[~] $ Curl-s 'http: // 10.232.41.142: 9001/hello1' [~] $ The server output log is as follows: $. /thread_http_server_error.pyquery:/hello1 thread = search041142.sqa.cm4.tbsite.net---[15/May/2014 15:02:27] "GET/hello1 HTTP/1.1" 200-success prod query:/hello1
2nd times curl, do not wait for the return, ctrl + C to simulate client disconnection
The code is as follows:
[~]$curl -s 'http://10.232.41.142:9001/hello2′[~]$ ctrl+C
The server output log is as follows:
The code is as follows:
query: /hello2 thread=search041142.sqa.cm4.tbsite.net – - [15/May/2014 15:33:10] “GET /hello2 HTTP/1.1″ 200 -socket.error : Connection broke. Aborting[Errno 32] Broken pipe—————————————-Exception happened during processing of request from ('10.232.41.142′, 48769)Traceback (most recent call last):File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 582, in process_request_threadself.finish_request(request, client_address)File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 323, in finish_requestself.RequestHandlerClass(request, client_address, self)File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/SocketServer.py”, line 639, in __init__self.handle()File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/BaseHTTPServer.py”, line 337, in handleself.handle_one_request()File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/BaseHTTPServer.py”, line 326, in handle_one_request self.wfile.flush() #actually send the response if not already done.File “/home/wuzhu/tools/python_2_7_1/lib/python2.7/socket.py”, line 303, in flushself._sock.sendall(view[write_offset:write_offset+buffer_size])AttributeError: 'NoneType' object has no attribute 'sendall'
2. cause analysis
The reason for "[Errno 32] Broken pipe" is clear. because the client proactively disconnects the connection before the server returns the result, the server writes the socket to report an error when receiving the SIGPIPE message. Although the exception is also handled in our program, the handler wfile. _ sock object closed, but BaseHTTPServer in the python library. in py, the BaseHTTPRequestHandler class member function handle_one_request still directly calls wfile. flush, but does not judge whether wfile has been closed.
The code is as follows:
Def handle_one_request (self): "" Handle a single HTTP request. you normally don't need to override this method; see the class _ doc _ string for information on how to handle specific HTTP commands such as GET and POST. "" try: self. raw_requestline = self. rfile. readline( 65537) if len (self. raw_requestline)> 65536: self. requestline = ''self. request_version = ''self. command = ''self. send_error (414) return if not self. raw_requestline: self. close_connection = 1 return if not self. parse_request (): # An error code has been sent, just exit return mname = 'do _ '+ self. command if not hasattr (self, mname): self. send_error (501, "Unsupported method (% r)" % self. command) return method = getattr (self, mname) method () # Call flush () self directly without judging whether wfile is close. wfile. flush () # actually send the response if not already done. using T socket. timeout, e: # a read or a write timed out. discard this connection self. log_error ("Request timed out: % r", e) self. close_connection = 1 return
3. Solution
You only need to reload the member function handle_one_reques () of the base class BaseHTTPRequestHandler in RequestHandler and add wfile close before calling wfile. flush.
The code is as follows:
#! /Usr/bin/env python #! Coding = utf-8import osimport timeimport socketimport threadingfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandlerfrom SocketServer import ThreadingMixInclass RequestHandler (BaseHTTPRequestHandler): def handle_one_request (self): "" Handle a single HTTP request. you normally don't need to override this method; see the class _ doc _ string for information on how to handle specific HTTP commands such as GET and POST. "" try: self. raw_requestline = self. rfile. readline( 65537) if len (self. raw_requestline)> 65536: self. requestline = ''self. request_version = ''self. command = ''self. send_error (414) return if not self. raw_requestline: self. close_connection = 1 return if not self. parse_request (): # An error code has been sent, just exit return mname = 'do _ '+ self. command if not hasattr (self, mname): self. send_error (501, "Unsupported method (% r)" % self. command) return method = getattr (self, mname) print "before call do_Get" method () # Add debug info and wfile to determine whether print has been closed "after call do_Get" if not self. wfile. closed: self. wfile. flush () # actually send the response if not already done. print "after wfile. flush () "socket T. timeout, e: # a read or a write timed out. discard this connection self. log_error ("Request timed out: % r", e) self. close_connection = 1 return def do_GET (self): "processing get requests" query = self. path print "query: % s thread = % s" % (query, str (threading. current_thread () ret_str =""+ Self. path +"
"+ Str (self. server) +""Time. sleep (5) try: self. send_response (200) self. send_header ('content-type', 'text/html ') self. end_headers () self. wfile. write (ret_str) into T socket. error, e: print "socket. error: Connection broke. aborting "+ str (e) self. wfile. _ sock. close () self. wfile. _ sock = None return False print "success prod query: % s" % (query) return True # multithreading class ThreadingHTTPServer (ThreadingMixIn, HTTPServer ): pass if _ name _ = '_ main _': serveraddr = ('', 9001) ser = ThreadingHTTPServer (serveraddr, RequestHandler) ser. serve_forever () sys. exit (0)
Running service
./Thread_http_server.py
Curl, do not wait to return, ctrl + C to simulate client disconnection
The code is as follows:
[~]$curl -s 'http://10.232.41.142:9001/hello2'[~]$ ctrl+C
The server output log is as follows:
$./thread_http_server.pybefore call do_Getquery: /hello2 thread=
search041142.sqa.cm4.tbsite.net - - [15/May/2014 15:54:09] "GET /hello2 HTTP/1.1" 200 -socket.error : Connection broke. Aborting[Errno 32] Broken pipeafter call do_Getafter wfile.flush()
The above is the content of the Python prompt [Errno 32] Broken pipe causes the thread crash error solution. For more information, see PHP Chinese network (www.php1.cn )!