我正在编写一个包含特定 Web 服务 API 的 Python 模块。这都是 REST,因此实现起来相对简单。
但是,在单元测试方面我发现了一个问题:由于我不运行我为这个模块创建的服务,我不想锤击它们,但同时,我需要检索数据来运行我的测试。我看了SimpleHTTPServer,没问题。
我解决了我遇到的部分问题,但是现在,由于我似乎无法终止线程,因此在多次启动测试应用程序时出现“地址已在使用”的问题。
这是一些示例代码
PORT = 8001
handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), handler)
httpd_thread = threading.Thread(target=httpd.serve_forever)
httpd_thread.setDaemon(True)
httpd_thread.start()
api_data = urllib.urlopen("http://localhost:8001/post/index.json")
print "Data start:"
print json.load(api_data)
其中“index.json”是我制作的模拟 JSON 文件,它替代了真实的东西。程序终止后如何优雅地清理东西?