【发布时间】:2020-03-01 01:42:50
【问题描述】:
我想在 Python 3.7 中的 asyncio 中运行 Tornado 服务器以及独立的长时间运行的任务。我是asyncio 的新手。我读过你应该只调用一次asyncio.run(),所以我将这两个任务放在main() 方法下,这样我就可以将一个参数传递给asyncio.run()。当我运行此代码时,我收到错误 TypeError: a coroutine was expected, got <function start_tornado at 0x105c8e6a8>。我想让代码在没有错误的情况下运行,但最终我想知道如何以正确的方式做到这一点。我在下面编写的代码感觉就像是一个丑陋的 hack。
import asyncio
import datetime
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
# Fake background task I got from here:
# https://docs.python.org/3/library/asyncio-task.html#sleeping
async def display_date():
while True:
print(datetime.datetime.now())
await asyncio.sleep(1)
async def start_tornado():
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
async def main():
await asyncio.create_task(start_tornado)
await asyncio.create_task(display_date)
asyncio.run(main())
【问题讨论】:
标签: python tornado python-asyncio