![](/img/trans.png)
[英]Flask and Tornado Applciation does not handle multiple concurrent requests
[英]Handle multiple incoming requests with Python tornado
我有一個適用於一個用戶請求的代碼。 但是,它不能處理多個請求,它等待一個請求完成,然后處理第二個請求。 如何同時處理多個請求。
import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado import gen
import random
import time
import sys
這是一個模擬某些傳入數據的類。
class Message():
def __init__(self):
self.dct = {'foo': 0, 'bar': 0, 'durrr': 0}
self.keys = list(self.dct.keys())
def update_key(self):
dct_key = random.choice(self.keys)
ran = random.choice(range(10, 21))
self.dct[dct_key] += ran
if self.dct[dct_key] >= 100:
self.dct[dct_key] = 'Loading Completed'
self.keys.remove(dct_key)
def is_completed(self):
return True if self.keys == [] else False
def __str__(self):
strng = ''
for key, value in self.dct.items():
if type(value) == int:
strng += '{}: {}% completed.<br>'.format(key, value)
else:
strng += '{}: {}<br>'.format(key, value)
return strng
此類通過套接字發送數據。
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
msg = Message()
while not msg.is_completed():
msg.update_key()
try:
fut = self.write_message('Download progress for user xyz:<br>{}Download in progress! Please wait...<br>'.format(msg.__str__()))
print(fut)
except tornado.websocket.WebSocketClosedError:
print('WebSocket is closed')
break
time.sleep(1)
self.write_message('Download progress for user xyz:<br>{}Download completed. You may proceed.'.format(msg.__str__()))
#sys.exit('Program terminated.')
def on_close(self):
print("WebSocket closed")
主類很簡單。 呈現一些html。 主機位於EchoWebSocket中。
class Main(tornado.web.RequestHandler):
def get(self):
self.render('counter2.html', title='Websockets')
application = tornado.web.Application([
(r"/", Main),
(r"/websocket", EchoWebSocket),
])
if __name__ == "__main__":
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
和html:
<!doctype html>
<html>
<head>
<title>Tornado Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
var ws = new WebSocket("ws://localhost:8888/websocket");
ws.onopen = function() {
ws.send("Hello, world");
};
ws.onmessage = function (evt) {
document.getElementById("myDIV").innerHTML = evt.data + "<br>";
};
});
</script>
<div id="myDIV"></div>
</body>
</html>
您正在使用time.sleep(1)
。 但是time.sleep
是一個阻止功能,這意味着它將停止整個服務器,並且在此期間將無法運行其他任何服務器。
在“龍卷風FAQs
頁面中也提到了這一點。
您需要的是異步睡眠功能。 龍卷風gen.sleep
。 像這樣使用它:
async def my_func():
...
await gen.sleep(1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.