python:任务产出不佳:

python: Task got bad yield:

我的目标是向端点列表发出并行请求,因此使用 asyncio ensure_future 可以请大家看一下并告诉我如何修复错误 (python3.6.7 )

import asyncio
import treq


async def main_aysnc():
    loop = asyncio.get_event_loop()
    await start_coros_parllel()

async def start_coros_parllel():
    config = {}
    config['services'] = [ 
        b'https://www.google.com',
        b'https://www.yahoo.com',
        b'https://www.facebook.com'
        ]
    results = await asyncio.gather(*[asyncio.ensure_future(treq.get(service)) for service in config['services']])
    

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main_aysnc())

日志

Traceback (most recent call last):
  File "2cr.py", line 35, in <module>
    asyncio.get_event_loop().run_until_complete(main_aysnc())
  File "/Users/vchauhan/.pyenv/versions/3.6.7/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
    return future.result()
  File "2cr.py", line 7, in main_aysnc
    await start_coros_parllel()
  File "2cr.py", line 20, in start_coros_parllel
    results = await asyncio.gather(*[asyncio.ensure_future(treq.get(service)) for service in config['services']])
  File "/Users/vchauhan/.pyenv/versions/3.6.7/lib/python3.6/asyncio/tasks.py", line 537, in _wrap_awaitable
    return (yield from awaitable.__await__())
RuntimeError: Task got bad yield: <Deferred at 0x104cc5048>

问题是您不应该将 asynciotreq 一起使用。

根据文档:

treq depends on a recent Twisted and functions on Python 2.7 and Python 3.3+ (including PyPy).

如果您想使用 asyncio,您必须使用其他一些 http 客户端框架,例如aiohttp.

如果您需要有关如何使用 aiohttp 客户端的任何示例,请随时询问。