簡體   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