Django + mod-wsgi + apache 在用户的一个请求中,我会向另一个服务发送另一个HTTP请求,并通过Python的httplib库解决此问题。
但有时这个服务的响应时间太长,而且httplib的超时不起作用。因此,我创建了一个线程,在这个线程中,我发送请求到服务,并在20秒后加入它(20秒是请求的超时时间)。这就是它的工作原理:
class HttpGetTimeOut(threading.Thread):
def __init__(self,**kwargs):
self.config = kwargs
self.resp_data = None
self.exception = None
super(HttpGetTimeOut,self).__init__()
def run(self):
h = httplib.HTTPSConnection(self.config['server'])
h.connect()
sended_data = self.config['sended_data']
h.putrequest("POST", self.config['path'])
h.putheader("Content-Length", str(len(sended_data)))
h.putheader("Content-Type", 'text/xml; charset="utf-8"')
if 'base_auth' in self.config:
base64string = base64.encodestring('%s:%s' % self.config['base_auth'])[:-1]
h.putheader("Authorization", "Basic %s" % base64string)
h.endheaders()
try:
h.send(sended_data)
self.resp_data = h.getresponse()
except httplib.HTTPException,e:
self.exception = e
except Exception,e:
self.exception = e
类似这样的内容...
并通过以下函数使用它:
getting = HttpGetTimeOut(**req_config)
getting.start()
getting.join(COOPERATION_TIMEOUT)
if getting.isAlive(): #maybe need some block
getting._Thread__stop()
raise ValueError('Timeout')
else:
if getting.resp_data:
r = getting.resp_data
else:
if getting.exception:
raise ValueError('REquest Exception')
else:
raise ValueError('Undefined exception')
一切工作正常,但有时我会开始捕获这个异常:
error: can't start new thread
在启动新线程的代码行:
getting.start()
接下来和最后一行回溯信息如下:
File "/usr/lib/python2.5/threading.py", line 440, in start
_start_new_thread(self.__bootstrap, ())
答案是:发生了什么?
感谢您所有的帮助,对于我的糟糕英语表示抱歉。 :)
threading.active_count()
显示正在运行的线程数。 - 101