【发布时间】:2022-01-07 13:40:06
【问题描述】:
我正在使用 python(3.8.8) aiohttp 和 asyncio 来发出异步 http 请求。 但是,当我尝试等待对 resp.content 的调用时,我会收到 TypeError: object StreamReader can't be used in 'await' expression
Traceback (most recent call last):
File "test_aiohttp.py", line 34, in get_country_wrapper
country_lst = await asyncio.gather(*result)
File "test_aiohttp.py", line 17, in get_country
html_text = await resp.content
TypeError: object StreamReader can't be used in 'await' expression
但是当我尝试等待调用 resp.json() 时,它可以工作。
async def get_country(session, url):
'''
Return the country of a given kaggle user
'''
async with session.get(url) as resp:
# json_resp = await resp.json()
html_text = await resp.content
country = re.search(r',"country":"([\w ]+)"', html_text)
return str(country.group(1))
async def get_country_wrapper(usernames):
try:
async with aiohttp.ClientSession() as session:
base_url = 'https://www.kaggle.com/'
result = []
for username in usernames:
url = base_url+str(username)
result.append(asyncio.create_task(get_country(session, url)))
country_lst = await asyncio.gather(*result)
return country_lst
except Exception as e:
print("Error: ", traceback.format_exc())
# Below is a sample list of users.
# Actual requirement is to run below for about 10,000 or more users
user_list = ['jhovey1', 'jsheppard95', 'dudihgustian', 'khmx5200', 'skshivamkedia']
asyncio.run(get_country_wrapper(user_list[:5]))
为什么我不能在这里使用像 resp.json() 这样的 resp.content?
(我使用 resp.content 而不是 resp.json() 的原因是后者给这个特定的 url 带来了错误)
我在下面的文章中引用了上面描述的 resp.json() 的用法。
https://www.twilio.com/blog/asynchronous-http-requests-in-python-with-aiohttp
https://itqna.net/questions/76711/error-requests-aiohttp-asyncio
【问题讨论】:
标签: python python-asyncio aiohttp