提到gen.coroutine装饰器来自旧版本。更新版本应与aysnc一起使用。到目前为止,我未能将那段小代码转换为Tornado 6.0.3。
import tornado.web
import tornado.websocket
import tornado.httpserver
from random import randint
from tornado import gen
from tornado.ioloop import IOLoop
from web_handlers import HandlerIndexPage
from web_handlers import HandlerWebSocket
msg = 'none'
@gen.coroutine
def generate_random_int():
global msg
while True:
msg = str(randint(0, 100))
print('generated:', msg)
yield gen.sleep(1.0)
@gen.coroutine
def generate_message_to_sockets():
global msg
while True:
print ('new messageToCon: ', msg)
yield [con.write_message(msg) for con in HandlerWebSocket.connections]
yield gen.sleep(1.0)
class webApplication(tornado.web.Application):
def __init__(self):
handlers = [
(r'/', HandlerIndexPage),
(r'/websocket', HandlerWebSocket)
]
settings = {
'template_path': 'templates'
}
tornado.web.Application.__init__(self, handlers, **settings)
if __name__ == '__main__':
ws_app = webApplication()
server = tornado.httpserver.HTTPServer(ws_app)
port = 9090
server.listen(port)
print('websocket listening on port:'+ str(port))
IOLoop.current().spawn_callback(generate_random_int)
IOLoop.current().spawn_callback(generate_message_to_sockets)
IOLoop.instance().start()
如何正确使用异步?
答案 0 :(得分:2)
在Tornado中,协程是可以插入Python2的生成器,而异步函数是Python3中的一等公民。它们具有不同的语义(例如,您可以通过异步函数return
,而不是协程)。您需要更改的代码如下所示:
...
import asyncio
...
async def generate_random_int():
global msg
while True:
msg = str(randint(0, 100))
print('generated:', msg)
await gen.sleep(1.0)
async def generate_message_to_sockets():
global msg
while True:
print ('new messageToCon: ', msg)
futures = [con.write_message(msg) for con in HandlerWebSocket.connections]
if futures:
await asyncio.wait(futures)
await gen.sleep(1.0)
...
您可以在此处看到类似于您的用例的示例:https://www.tornadoweb.org/en/stable/ioloop.html#ioloop-objects
答案 1 :(得分:1)
Python 3.5 引入了 function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<Router>
<div className="App">
{/* Navbar */}
<Navbar/>
{/* Pages */}
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
{/* Admin Pages */}
<Route path="/Admin/Login" exact component={Login}/>
<ProtectedRoute path="/Admin/Dashboard" component={Dashboard} isLoggedIn={isLoggedIn}/>
{/*404 Not Found Page*/}
<Route path="*" component={Page404} />
</Switch>
</div>
</Router>
);
}
和 async
关键字(使用这些关键字的函数也称为“原生协程”)。
await