为什么在Python BaseHTTPServer中会出现随机读取错误?
我有一段Python代码,它会调用外部的HTTP服务。我想通过设置模拟的HTTP服务器来测试这段代码,这些模拟服务器可以模仿那些外部服务。我是通过在一个单独的线程中启动一个BaseHTTPServer
,然后在主线程中调用这个服务器来实现的。代码大致是这样的:
import BaseHTTPServer, httplib, threading, time
class MockHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write('{"result": "success"}')
class ServerThread(threading.Thread):
def run(self):
svr = BaseHTTPServer.HTTPServer(('127.0.0.1', 8540), MockHandler)
svr.handle_request()
ServerThread().start()
time.sleep(0.1) # Give the thread some time to get up
conn = httplib.HTTPConnection('127.0.0.1', 8540)
conn.request('POST', '/', 'foo=bar&baz=qux')
resp_body = conn.getresponse().read()
不过,有些请求在read()
调用时会失败,出现socket.error: [Errno 104] Connection reset by peer
的错误。我在几台使用Python 2.6的机器上都能复现这个问题,频率不一,但在2.7上就没有这个问题。
最有意思的是,如果我不发送POST数据(也就是在调用conn.request()
时不传第三个参数),这个错误就不会出现。
这可能是什么原因呢?
另外,有没有其他简单快捷的方法可以在Python中设置模拟的HTTP服务器呢?
1 个回答
1
“...在一个单独的线程中,然后从主线程调用那个服务器。”
不要用线程来处理这种事情。
应该使用进程。subprocess.Popen
(还有你操作系统的正常功能)会更好地确保这个工作正常。