繁体   English   中英

如何在 Python 中调用从异步 function 返回的 object 的方法?

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

我得到了这个 function:

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

要获取数据,我需要编写:

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

如何更改download以便我可以这样写

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

没有得到AttributeError: 'coroutine' object has no attribute 'text'吗?

可能这有助于简化使用:

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()

然后使用它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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