次の構成で実行されるサイトがあります。
Django + mod-wsgi + Apache
ユーザーのリクエストの 1 つで、別のサービスに別の 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, ())
答えは次のとおりです。
すべてに感謝し、私の純粋な英語で申し訳ありません。:)