【问题标题】:Tornado Asynchronous simple programTornado 异步简单程序
【发布时间】:2020-09-19 10:19:16
【问题描述】:

我需要这个简单程序的帮助,我不确定这个 tornado 应用程序是否是异步的(我添加了 async/await),但我相信我应该添加一些东西。 我希望程序异步监听请求,提前谢谢。

import tornado.web
import tornado.ioloop
import fun, func2

class A(tornado.web.Application):
    async def post(self):
        result = await func2()

class B(tornado.web.Application):
    async def put(self):
        result = await func()

def main():
    app = tornado.web.Application([
        (r"/A", A),
        (r"/B", B)
    ])
    return app


if __name__ == "__main__":
    app = main()
    app.listen(8000)
    tornado.ioloop.IOLoop.current().start()

【问题讨论】:

标签: python asynchronous async-await tornado


【解决方案1】:

您不应使用两个应用程序,而应使用一个具有两个处理程序的应用程序。 如果需要,处理程序方法可以是异步的。 Tornado 从地面支持这一点。

所以可能更像这样,taken from the tornado docs

典型的 WebApp 骨架:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHandler),
    ])
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

async handler method 的示例

from tornado.httpclient import AsyncHTTPClient

async def asynchronous_fetch(url):
    http_client = AsyncHTTPClient()
    response = await http_client.fetch(url)
    return response.body

所以对于你的例子,这看起来更像这样

import tornado.ioloop
import tornado.web
from tornado.httpclient import AsyncHTTPClient

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

class AsyncHandler(tornado.web.RequestHandler):
    async def get(self):
        http_client = AsyncHTTPClient()
        response = await http_client.fetch("<some_url")
        return response.body

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/", MainHandler),
        (r"/async", AsyncHandler),
    ])
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()

您必须确保在 async 方法中使用的每个模块或库都是 还有async 并且在结束请求之前不会阻止呼叫。对于您使用的任何 I/O 来说尤其如此。包括文件、web请求、数据库访问等。

【讨论】:

    猜你喜欢
    • 2011-06-23
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 2016-02-23
    • 2012-10-14
    • 1970-01-01
    相关资源
    最近更新 更多