tornado 异步装饰器
时间: 2023-09-01 21:11:31 浏览: 53
tornado 中的异步装饰器包括两种:`@gen.coroutine` 和 `@gen.asynchronous`。
`@gen.coroutine` 是 tornado 最早引入的异步装饰器,它将函数标记为可暂停的协程。使用该装饰器修饰的函数可以在其中使用 `yield` 关键字来暂停执行,等待异步操作完成后再继续执行。示例代码如下:
```python
from tornado import gen
@gen.coroutine
def async_func():
yield some_async_operation()
```
`@gen.asynchronous` 是 tornado 更加新的异步装饰器,它的作用与 `@gen.coroutine` 类似,但是需要手动在函数中调用 `self.finish()` 来结束请求处理。示例代码如下:
```python
from tornado import gen
class AsyncHandler(RequestHandler):
@gen.asynchronous
def get(self):
result = yield some_async_operation()
self.write(result)
self.finish()
```
需要注意的是,使用 `@gen.asynchronous` 装饰器时,必须手动调用 `self.finish()` 来结束请求处理。否则,请求将一直处于挂起状态,直到超时或其他错误发生。
相关问题
tornado6 异步装饰器 asynchronous
在 Tornado6 中,异步装饰器被称为 `asynchronous`。使用 `asynchronous` 装饰器可以将函数转换为协程。这个装饰器告诉 Tornado,这个函数是一个异步函数,需要使用协程进行处理。
例子:
```python
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
async def get(self):
# 异步操作
self.write("Hello, world")
self.finish()
if __name__ == "__main__":
app = tornado.web.Application([
(r"/", MainHandler),
])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
```
在上面的例子中,`get` 函数被 `asynchronous` 装饰器装饰,标志着这个函数是异步的。在这个函数中,我们可以使用 `await` 来等待异步操作完成。当异步操作完成时,我们调用 `self.write` 和 `self.finish` 函数来输出响应内容并完成请求。
tornado 如何实现异步并行非阻塞server sent events
Tornado可以通过`@tornado.web.stream_request_body`装饰器来实现异步并行非阻塞的Server-Sent Events。具体步骤如下:
1. 创建一个继承自`tornado.web.RequestHandler`的类,添加`@tornado.web.stream_request_body`装饰器。
```python
import tornado.web
class SSEHandler(tornado.web.RequestHandler):
@tornado.web.stream_request_body
def post(self):
pass
```
2. 在`post`方法中,使用`tornado.ioloop.IOLoop.current().spawn_callback`方法来异步执行数据的生成和推送,并使用`tornado.web.RequestHandler.flush`方法将数据发送给客户端。
```python
import tornado.web
import tornado.ioloop
class SSEHandler(tornado.web.RequestHandler):
@tornado.web.stream_request_body
def post(self):
self.set_header('Content-Type', 'text/event-stream')
self.set_header('Cache-Control', 'no-cache')
self.set_header('Connection', 'keep-alive')
def generate_data():
data = 'data: Hello, world!\n\n'
self.write(data)
self.flush()
tornado.ioloop.IOLoop.current().spawn_callback(generate_data)
```
在这个例子中,我们设置了响应头,告诉客户端我们要发送的是Server-Sent Events。然后在`generate_data`函数中,生成一条消息并使用`write`方法将其写入响应中,再使用`flush`方法将数据发送给客户端。最后,在`post`方法中使用`IOLoop.current().spawn_callback`方法来异步执行`generate_data`函数。
3. 在客户端使用`EventSource`对象来接收推送的数据。
```javascript
var source = new EventSource('/sse');
source.onmessage = function(event) {
console.log(event.data);
};
```
在客户端中,我们使用`EventSource`对象来向服务器发送请求,并监听`onmessage`事件来接收推送的数据。在接收到数据时,我们可以在控制台中打印出来。
以上就是使用Tornado实现异步并行非阻塞的Server-Sent Events的步骤。在实际应用中,可以在`generate_data`函数中根据需要生成不同的数据,并使用`write`和`flush`方法将数据推送给客户端。