通过异步调用时,Python 会给出不同的响应

问题描述 投票:0回答:1

相同的逻辑得到不同的输出? 正在尝试学习 python 中的 async/await。

第一个片段的输出:

<class 'dict'>
第二个片段的输出:
<class 'list'>


片段 1:无异步

import urllib.request
import json

def get_response(user_url):
    resp = urllib.request.urlopen(user_url).read()
    resp_json = json.loads(resp)
    return resp_json['results'][0]


def make_request(user_url):
    json_response = get_response(user_url)
    print(type(json_response))

USER_URL = 'https://randomuser.me/api'
make_request(USER_URL)

片段 2:使用异步

import urllib.request
import json
import asyncio

async def get_response(user_url):
    resp = urllib.request.urlopen(user_url).read()
    resp_json = json.loads(resp)
    return resp_json['results'][0]


async def make_request(user_url):
    json_response = await asyncio.gather(get_response(user_url))
    print(type(json_response))

USER_URL = 'https://randomuser.me/api'
asyncio.run(make_request(USER_URL))

为什么我们在代码中相同的逻辑会得到不同的输出? 期望获得两者的 dict 数据类型。

使用Python 3.10

python python-3.x dictionary async-await concurrency
1个回答
0
投票

那个

<class 'list'>
asyncio.gather()
的返回值。

如果您只有一个 URL,

await get_response(user_url)
就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.