我有一个使用以下配置运行的站点:
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, ())
答案是:发生了什么?
谢谢大家,对不起我纯正的英语。:)