简体   繁体   中英

How to call a method of an object returned from an async function without parentheses in Python?

I got this function:

async def download(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            if resp.status == 200:
                return resp

To get the data, I'd need to write:

text = await (await utils.download(url)).text()

How to change download so I can write like this

text = await utils.download(url).text()

without getting AttributeError: 'coroutine' object has no attribute 'text' ?

May be this can help simplifying the usage:

async def download(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            if resp.status == 200:
                return await resp.text()

Then to use it:

async def main():
    text = await download("http://python.org")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM