0

我正在创建一个与 API 通信的模块,并且我正在考虑使用 asyncio 创建我的函数。现在我的代码看起来像这样:

def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    res = requests.get(endpoint, params=params, headers=header)
    return res

如您所见,我正在使用请求模块来发送数据。我认为我需要这样做:

import asyncio
async def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    res = requests.get(endpoint, params=params, headers=header)
    yield res

这会使我的函数异步吗?还是我也应该使用 httpx(或 aiohttp)之类的东西来等待结果?像下面这样

async def getMethod(self, stuff:str=None): #yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    await res = httpx.get(endpoint, params=params, headers=header)
    return res

谢谢你的帮助。试图在那里学习异步python。

4

1 回答 1

0

建议使用 httpx,异步代码如下:

async def getMethod(self, stuff: str = None):  # yes it in a class
    header = {'Content-Type': 'application/json'}
    endpoint = f"https://{self.endpoint}/"
    params = {"myParam": stuff}
    async with httpx.AsyncClient(headers=header, params=params) as client:
        res = await client.get(endpoint, params=params, headers=header)
    return res
于 2021-11-16T12:54:30.033 回答