我有以下資源來處理與扭曲網頁的HTTP POST請求:陸續Twisted web - write()在finish()之後調用?
class RootResource(Resource):
isLeaf = True
def errback(self, failure):
print "Request finished with error: %s"%str(failure.value)
return failure
def write_response_happy(self, result):
self.request.write('HAPPY!')
self.request.finish()
def write_response_unhappy(self, result):
self.request.write('UNHAPPY!')
self.request.finish()
@defer.inlineCallbacks
def method_1(self):
#IRL I have many more queries to mySQL, cassandra and memcache to get final result, this is why I use inlineCallbacks to keep the code clean.
res = yield dbpool.runQuery('SELECT something FROM table')
#Now I make a decision based on result of the queries:
if res: #Doesn't make much sense but that's only an example
self.d.addCallback(self.write_response_happy) #self.d is already available after yield, so this looks OK?
else:
self.d.addCallback(self.write_response_unhappy)
returnValue(None)
def render_POST(self, request):
self.request = request
self.d = self.method_1()
self.d.addErrback(self.errback)
return server.NOT_DONE_YET
root = RootResource()
site = server.Site(root)
reactor.listenTCP(8002, site)
dbpool = adbapi.ConnectionPool('MySQLdb', host='localhost', db='mydb', user='myuser', passwd='mypass', cp_reconnect=True)
print "Serving on 8002"
reactor.run()
我使用了AB工具(從阿帕奇utils的)來測試5 POST請求之一:
ab -n 5 -p sample_post.txt http://127.0.0.1:8002/
工作正常!
然後我試圖同時運行相同的5 POST請求:
ab -n 5 -c 5 -p sample_post.txt http://127.0.0.1:8002/
在這裏,我得到錯誤:exceptions.RuntimeError:Request.write呼籲請求Request.finish被稱爲後。我究竟做錯了什麼?
您可能需要您的結果記錄併發訪問:用'完成關閉它()',而其他請求試圖在它來寫。 – Mualig
是的,我有併發訪問,我一次運行5個請求。我是扭曲網絡的新手,如果我有併發請求會發生什麼?我不是每次都得到一個單獨的Resource類實例嗎? – PawelRoman
由於您只有1個'RootResource'鏈接到您的'reactor',它們監聽您的TCP請求。恕我直言,你只有1'創建了'資源'。嘗試評論'Finish()',並在收到所有請求後立即執行。 – Mualig