如何将协程转换为 Python 中的列表?
How to convert a coroutine to a list in Python?
我使用 aiohttp 库,我从服务器接收 json 格式的数据。在所有数据中,我只需要两个需要显示在列表中的字段。但是当函数被调用时,协程被返回。我如何取回列表?
async def request_geocoder_api(city):
url = f"https://nominatim.openstreetmap.org/search?city={city}&format=json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response_json = await response.json
latitude = response_json[0]['lat']
longitude = response_json[0]['lon']
return [latitude, longitude]
函数调用:
answer_list = await request_geocoder_api(answer)
错误:
TypeError: object method can't be used in 'await' expression
要获取可等待协程,请调用json()
函数。您缺少 ()
并且只是获取函数“指针”。
response_json = await response.json()
我使用 aiohttp 库,我从服务器接收 json 格式的数据。在所有数据中,我只需要两个需要显示在列表中的字段。但是当函数被调用时,协程被返回。我如何取回列表?
async def request_geocoder_api(city):
url = f"https://nominatim.openstreetmap.org/search?city={city}&format=json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
response_json = await response.json
latitude = response_json[0]['lat']
longitude = response_json[0]['lon']
return [latitude, longitude]
函数调用:
answer_list = await request_geocoder_api(answer)
错误:
TypeError: object method can't be used in 'await' expression
要获取可等待协程,请调用json()
函数。您缺少 ()
并且只是获取函数“指针”。
response_json = await response.json()