0

SyntaxError: 'yield from' 在异步函数中

async def handle(request):
    for m in (yield from request.post()):
        print(m)
    return web.Response()

之前用过python3.5,发现pep525,安装python3.6.5还是报这个错。

4

1 回答 1

2

您正在使用新的async/await语法来定义和执行协同例程,但尚未进行完全切换。你需要在await这里使用:

async def handle(request):
    post_data = await request.post()
    for m in post_data:
        print(m)
    return web.Response()

如果您想坚持旧的 Python 3.5 之前的语法,请使用@asyncio.coroutine装饰器将您的函数标记为协程,删除async关键字,并使用yield from代替await

@async.coroutine
def handle(request):
    post_data = yield from request.post()
    for m in post_data:
        print(m)
    return web.Response()

但是这种语法正在逐步淘汰,并且不像新语法那样易于发现和可读。仅当您需要编写与旧 Python 版本兼容的代码时,才应使用此表单。

于 2018-07-29T19:56:35.587 回答