我有调用外部 HTTP 服务的 Python 代码。我想通过设置模仿这些外部服务的模拟 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 服务器的快速简便的方法?
最佳答案
“...在一个单独的线程中,然后从主线程调用该服务器。”
不要为这种事情使用线程。
使用流程。 subprocess.Popen
(以及您的操作系统的正常功能)将更好地确保其正常工作。
关于python - 为什么我看到 Python BaseHTTPServer 出现随机读取错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6697390/