在用 Sanic 的时候 报错 TypeError coroutine object is not iterable

发布于 2022-09-06 12:28:41 字数 4288 浏览 19 评论 0

在用 sanic 做一个小项目的时候, 碰到上面这个问题。这是其中一个 views:

@app.route("/query_video/", methods=["GET"])
async def video_query_views(request: Request):
    keyword = request.args.get("keyword", None)
    page = request.args.get("page", None)
    order = request.args.get("order", None)
    query_params = dict()
    if keyword:
        query_params['keyword'] = keyword
    else:
        return json("keyword can't be empty", status=403)
    if page:
        query_params['page'] = page
    if order:
        query_params['order'] = order
    try:
        rest = dict()
        rest['bilibili'] = await get_bilibili_query(**query_params)
        rest['qq'] = await get_v_qq_query(**query_params)
        rest['youku'] = await get_youku_query(**query_params)
        rest['iqiyi'] = await get_iqiyi_query(**query_params)
        rest['mg'] = await get_mgtv_query(**query_params)
    except Exception as e:
        print(traceback.format_exc())
        return json(str(e), status=403)
    return json(rest)
    

其中get_bilibili_query, get_v_qq_query之类的都是一个aiohttp 写小爬虫,具体:

async def get_bilibili_query(keyword, page=1, order='tolalrank'):
    base_url = "https://search.bilibili.com/all"
    query_params = {
        "keyword": keyword,
        "page": page,
        "order": order,
    }
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url=base_url, params=query_params)
    html = etree.HTML(html)
    lis = html.xpath("//li[@class='video matrix ']")
    rst = list()
    for li in lis:
        try:
            a = li.xpath('a')[0]
            img = a.xpath('div/img')[0]

            time_len = a.xpath('div/span/text()')[0].strip()
            title = a.xpath("@title")[0].strip()
            origin_url = urljoin(base_url, a.xpath('@href')[0].strip())
            img_url = urljoin(base_url, img.xpath("@data-src")[0].strip())
            rst.append({
                'origin_url': origin_url,
                'time_len': time_len,
                'img_url': img_url,
                'title': title
            })
        except Exception:
            continue
    else:
        return rst
        

报错在 fetch 函数中:

async def fetch(session, url, **kwargs):
    with async_timeout.timeout(10):
        async with session.get(url, **kwargs, verify_ssl=False) as response:
            return await response.text()

具体错误如下:

Traceback (most recent call last):
  File "/Users/angelo/PycharmProjects/pp3/s1.py", line 51, in video_query_views
    rest['iqiyi'] = await get_iqiyi_query(**query_params)
  File "/Users/angelo/PycharmProjects/pp3/sp.py", line 25, in get_bilibili_query
    html = await fetch(session, url=base_url, params=query_params)
  File "/Users/angelo/PycharmProjects/pp3/sp.py", line 13, in fetch
    async with session.get(url, **kwargs, verify_ssl=False) as response:
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/client.py", line 690, in __aenter__
    self._resp = yield from self._coro
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/client.py", line 267, in _request
    conn = yield from self._connector.connect(req)
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/connector.py", line 402, in connect
    proto = yield from self._create_connection(req)
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/connector.py", line 748, in _create_connection
    _, proto = yield from self._create_direct_connection(req)
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/connector.py", line 831, in _create_direct_connection
    req=req, client_error=client_error)
  File "/Users/angelo/PycharmProjects/env3.5/lib/python3.5/site-packages/aiohttp/connector.py", line 796, in _wrap_create_connection
    return (yield from self._loop.create_connection(*args, **kwargs))
TypeError: 'coroutine' object is not iterable

感觉错误 报的很奇怪,当我直接用 aiohttp 的 web 执行的时候,是没有问题的,直接 loop 执行也没有问题。只有 sanic 执行的时候会报错,但报错是在aiohttp 中报的。

loop = asyncio.get_event_loop()
    loop.run_until_complete(get_bilibili_query(keyword='python'))

这么执行时不会报错。
求助。。。。

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱成瘾 2022-09-13 12:28:41

在Python3.5以后,原生协程不能用于迭代,未被装饰的生成器不能yield from一个原生协程

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文