Python异步AttributeError退出 [英] Python async AttributeError aexit

查看:99
本文介绍了Python异步AttributeError退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我总是收到错误 AttributeError:__aexit __ ,但是我真的不明白为什么会发生这种情况.

I keep getting error AttributeError: __aexit__ on the code below, but I don't really understand why this happens.

我的Python版本是: 3.6.4(v3.6.4:d48eceb,2017年12月19日,06:04:45)[MSC v.1900 32位(Intel)]

My Python version is: 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)]

import aiohttp
import asyncio
import tqdm


async def fetch_url(session_, url_, timeout_=10):
    with aiohttp.Timeout(timeout_):
        async with session_.get(url_) as response:
            text = await response.text()
            print("URL: {} - TEXT: {}".format(url_, len(text)))
            return text


async def parse_url(session, url, timeout=10):
    # get doc from url
    async with await fetch_url(session, url, timeout) as doc:
        print("DOC: {}".format(doc, len(doc)))
        return doc


async def parse_urls(session, urls, loop):
    tasks = [parse_url(session, url) for url in urls]
    responses = [await f for f in tqdm.tqdm(asyncio.as_completed(tasks), total = len(tasks))]
    return responses


if __name__ == '__main__':

    tickers = ['CTXS', 'MSFT', 'AAPL', 'GPRO', 'G', 'INTC', 'SYNC', 'SYNA']
    urls = ["https://finance.yahoo.com/quote/{}".format(ticker) for ticker in tickers]

    loop = asyncio.get_event_loop()
    with aiohttp.ClientSession(loop=loop) as session:
        parsed_data = loop.run_until_complete(parse_urls(session, urls, loop))
        print(parsed_data)

错误调用栈:

C:\Python\Python36\python.exe C:/Users/me/.PyCharmCE2017.3/config/scratches/scratch_4.py
  0%|          | 0/8 [00:00<?, ?it/s]Traceback (most recent call last):
URL: https://finance.yahoo.com/quote/CTXS - TEXT: 462138
  File "C:/Users/me/.PyCharmCE2017.3/config/scratches/scratch_4.py", line 34, in <module>
    parsed_data = loop.run_until_complete(parse_urls(session, urls, loop))
  File "C:\Python\Python36\lib\asyncio\base_events.py", line 467, in run_until_complete
    return future.result()
  File "C:/Users/me/.PyCharmCE2017.3/config/scratches/scratch_4.py", line 23, in parse_urls
    responses = [await f for f in tqdm.tqdm(asyncio.as_completed(tasks), total = len(tasks))]
  File "C:/Users/me/.PyCharmCE2017.3/config/scratches/scratch_4.py", line 23, in <listcomp>
    responses = [await f for f in tqdm.tqdm(asyncio.as_completed(tasks), total = len(tasks))]
  File "C:\Python\Python36\lib\asyncio\tasks.py", line 458, in _wait_for_one
    return f.result()  # May raise f.exception().
  File "C:/Users/me/.PyCharmCE2017.3/config/scratches/scratch_4.py", line 16, in parse_url
    async with await fetch_url(session, url, timeout) as doc:
AttributeError: __aexit__


Process finished with exit code 1

推荐答案

您正在尝试使用 fetch_url 作为上下文管理器,但这不是一个.您可以将其设为

You are trying to use fetch_url as a context manager, but it isn't one. You can either make it one

class fetch_url:
    def __init__(self, session, url, timeout=10):
        self.session = session
        self.url = url
        self.timeout = timeout

    async def __aenter__(self):
        with aiohttp.Timeout(self.timeout):
            async with self.session.get(self.url) as response:
                text = await response.text()
                print("URL: {} - TEXT: {}".format(self.url, len(text)))
                return text

    async def __aexit__(self, exc_type, exc, tb):
        # clean up anything you need to clean up

或将代码更改为

async def parse_url(session, url, timeout=10):
    # get doc from url
    doc = await fetch_url(session, url, timeout)
    print("DOC: {}".format(doc, len(doc)))
    return doc

这篇关于Python异步AttributeError退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆