我如何 运行 Tornado 的 IOLoop 的多个实例?

How can I run multiple instances of Tornado's IOLoop?

我有一个用 Tornado 编写的基本 Web 服务器。现在,我想添加一些需要数据库连接的功能。我选择了 MongoDB 和 Motor 库。在关注 official tutorial 之后,我的 main.py 的相关部分看起来像:

class LoginHandler(BaseHandler):

    async def get(self):

        db = self.settings['db']
        collection = db.test

        async def do_find_one():
            document =  await collection.find_one({"ime" : "stefan"})
            pprint.pprint(document)

        self.render('login.html')



def main():
    parse_command_line()

    client = motor.motor_tornado.MotorClient('localhost',27017)
    db = client.test
    collection = db.test

    async def do_find_one():
        document =  await collection.find_one({"name" : "John"})
        pprint.pprint(document)

    settings = {
        "template_path": os.path.join(os.path.dirname(__file__),"templates"),
        "cookie_secret": "random_value_goes_here",
        "xsrf_cookies": True,
        "login_url": "/login",
        "db" : db,
        "debug" : True
    }

    app = tornado.web.Application([
        (r'/', WelcomeHandler),
        (r'/login', LoginHandler)
        ],
        **settings
    )

    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()

按照教程,它指出我现在可以 运行 do_find_one 使用 IOLoop.current().run_sync(do_find_one)。但是,如果我这样做:

tornado.ioloop.IOLoop.current().start()
tornado.ioloop.IOLoop.current().run_sync(do_find_one)

它不会改变任何东西,也看不到足够的结果,但是如果换行,比如:

tornado.ioloop.IOLoop.current().run_sync(do_find_one)
tornado.ioloop.IOLoop.current().start()

我收到以下错误:

Traceback (most recent call last):
  File "main.py", line 108, in <module>
    main()
  File "main.py", line 102, in main
    tornado.ioloop.IOLoop.current().run_sync(do_find_one)
NameError: name 'do_find_one' is not defined

我是否应该在 main 中定义 do_find_one() 函数,然后在 LoginHandlerget 方法中 await 它?

如何让服务器工作,同时操作数据库?

这些 IOLoops 运行 可以在同一个线程上吗,或者我需要创建多个线程(每个 IOLoop 或类似线程一个)?

当循环开始后,您应该能够只await异步函数而不必知道哪个是当前异步循环。

async def do_find_one(collection):
    document = await collection.find_one({"ime": "stefan"})
    pprint.pprint(document)
    return 8


class LoginHandler(BaseHandler):
    async def get(self):
        db = self.settings["db"]
        val = await do_find_one(collection=db.test)
        print(val)
        self.render("login.html")


handlers = [(r"/", WelcomeHandler), (r"/login", LoginHandler)]


def make_app(settings):
    return tornado.web.Application(handlers, **settings)


def main():
    parse_command_line()
    client = motor.motor_tornado.MotorClient("localhost", 27017)
    db = client.test

    settings = {
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "cookie_secret": "random_value_goes_here",
        "xsrf_cookies": True,
        "login_url": "/login",
        "db": db,
        "debug": True,
    }
    app = make_app(settings)
    app.listen(options.port)
    tornado.ioloop.IOLoop.current().start()


if __name__ == "__main__":
    main()