1

好吧,这很奇怪,但是这里有——

import asyncio

from starlette.applications import Starlette


class MyTasks:
    def __init__(self):
        self.task = None

    async def main(self):
        self.task = asyncio.create_task(self.hello())

    async def hello(self):
        raise ValueError


async def main():
    await MyTasks().main()


app = Starlette(on_startup=[main])

$ uvicorn test:app
INFO:     Started server process [26622]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

嗯,ValueError这里没有……


self.task现在,删除对in的分配MyTasks.main()

    async def main(self):
        asyncio.create_task(self.hello())
    ...

$ uvicorn test:app
INFO:     Started server process [29083]
INFO:     Waiting for application startup.
ERROR:    Task exception was never retrieved
future: <Task finished name='Task-3' coro=<MyTasks.hello() done, defined at ./test.py:13> exception=ValueError()>
Traceback (most recent call last):
  File "./test.py", line 14, in hello
    raise ValueError
ValueError
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

……瞧。


这里发生了什么?该分配如何产生或破坏异常记录!?

4

2 回答 2

2

任务是未来的子类,这意味着它具有结果的概念。在任务的情况下,结果是它驱动的协程返回的值。如果协程引发异常,则异常被封装在任务对象中。正确编写的代码最终会等待任务或访问其结果,以便异常不会静默传递。

为了帮助调试忘记访问任务的代码,如果任务引发异常但从未等待,任务的析构函数会记录错误。在运行析构函数之前无法记录此错误,因为只要您的代码保留任务对象,就可以在任何时候等待它。析构函数运行的时间点是 Python 能够可靠地“证明”任务未等待的第一个实例。

但是这个最后的日志记录不是你应该依赖的,它是在尽力而为的基础上提供的。例如,由于 GC,可能会推迟运行析构函数。我希望将任务分配给绑定方法由任务驱动的实例会使任务成为参考周期的一部分。这会将析构函数的运行推迟到完整的 GC 之后,并且您看不到日志。

要解决此问题,您应该在协程中捕获异常并自己记录它们,而不是让它们传播,或者在代码中的某个位置实际等待任务。

于 2020-02-19T07:11:21.100 回答
1

抱歉,这是另一个问题的欺骗。

asyncio.create_task() 已在此处发布了替代品。


这是使用替换后的输出create_task()

案例一:有await self.task

$ uvicorn test:app
INFO:     Started server process [33213]
INFO:     Waiting for application startup.
ERROR:    Traceback (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 517, in lifespan
    await self.startup()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/starlette/routing.py", line 494, in startup
    await handler()
  File "./test.py", line 35, in main
    await MyTasks().main()
  File "./test.py", line 27, in main
    print(await self.task)
  File "./test.py", line 13, in wrapper
    return await task
  File "./test.py", line 30, in hello
    raise ValueError
ValueError

ERROR:    Application startup failed. Exiting.

案例2:没有await self.task

$ uvicorn test:app
INFO:     Started server process [32627]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
ERROR:    Exception in callback <function create_task.<locals>.on_done at 0x10c519550>
handle: <Handle create_task.<locals>.on_done created at /Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py:382>
source_traceback: Object created at (most recent call last):
  File "/Users/dev/.virtualenvs/server-99338def/bin/uvicorn", line 8, in <module>
    sys.exit(main())
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 717, in main
    rv = self.invoke(ctx)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/click/core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 331, in main
    run(**kwargs)
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 354, in run
    server.run()
  File "/Users/dev/.virtualenvs/server-99338def/lib/python3.8/site-packages/uvicorn/main.py", line 382, in run
    loop.run_until_complete(self.serve(sockets=sockets))
Traceback (most recent call last):
  File "uvloop/cbhandles.pyx", line 70, in uvloop.loop.Handle._run
  File "./test.py", line 9, in on_done
    fut.result()
  File "./test.py", line 30, in hello
    raise ValueError
ValueError
于 2020-02-19T13:31:37.943 回答