发送多个httplib请求,引发回溯异常

时间:2011-11-02 14:57:59

标签: python django httplib

以下是代码:

conn = httplib.HTTPConnection("127.0.0.1:8000")
conn.request("POST", "/api/job/", some_params, headers)
conn.close()

向服务器发送请求没问题

但如果我使用循环例如:

for i in range(n):
   conn = httplib.HTTPConnection("127.0.0.1:8000")
   conn.request("POST", "/api/job/", some_params, headers)
   conn.close()

它引发了异常,但有趣的是请求成功了:

Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 284, in run
self.finish_response()
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 324, in finish_response
self.write(data)
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 403, in write
self.send_headers()
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 467, in send_headers
self.send_preamble()
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 385, in send_preamble
'Date: %s\r\n' % http_date()
File "/usr/lib/python2.7/socket.py", line 324, in write
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 60438)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 310, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 570, in __init__
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 641, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 694, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------

任何建议???

1 个答案:

答案 0 :(得分:1)

在我看来,你的缓冲区已经被填满了。您的缓冲区将填充您所做的任何网络请求,然后在服务器确认收到数据时清除。不确定是否有更好的方法可以做到这一点,但您可以尝试通过在循环中执行简短time.pause来给服务器一些时间来确认收到。