当前正在使用 aiohttp 构建异步 API 包装器,并且请求参数存在默认值为“None”的问题
import asyncio
import aiohttp
class AsyncWrapper:
def __init__(self, api_key, useragent="API-Wrapper/0.2"):
self.url = f"https://example.api/v1"
self._api_key = api_key
self._useragent = useragent
self._headers = {"X-API-Key": self._api_key, "accept": "application/json", "User-Agent": self._useragent}
self._session = aiohttp.ClientSession()
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
async def close(self):
await self._session.close()
async def get_endpoint1(self, arg1, arg2):
endpoint = "/pair"
async with self._session.get(self.url + endpoint, params={"arg1": arg1, "arg2": arg2}, headers=self._headers) as response:
return await response.json()
async def get_endpoint2(self, arg1, arg2, optionalarg1=None, optionalarg2=None):
endpoint = "/token"
async with self._session.get(self.url + endpoint, params={"arg1": arg1, "arg2": arg2, "optionalarg1": optionalarg1, "optionalarg2": optionalarg2}, headers=self._headers) as response:
return await response.json()
get_endpoint1
完美工作,因为参数的现有参数是字符串类型
get_endpoint2
但是,参数有两个可选参数,如果未指定,则默认为“None”(NoneType)。
运行此代码时我得到:
TypeError: Invalid variable type: value should be str, int or float, got None of type <class 'NoneType'>
在 Python 的“requests”模块中,如果您使用 NoneType 添加参数,它会忽略它们并且不会在 url 请求上对它们进行编码。
我能想到解决此问题的唯一选择是添加条件检查,其中传递的参数包含“None”,如果包含“None”,则不要将其添加到 params 字典中。
但我想知道是否有另一种方法或解决方法。我相信 requests 模块可以很好地处理这个问题。
请随时添加对现有代码的任何反馈
谢谢你。
如果你经常使用它,你可以创建一个小函数,如下所示:
def params(**kwargs):
return {k, v for k, v in kwargs.items() if v is not None and v != ""}
然后简单地使用它:
self._session.get(
self.url + endpoint,
params=params(
arg1=arg1, arg2=arg2, optionalarg1=optionalarg1,
optionalarg2=optionalarg2),
headers=self._headers)
我认为这可能是你能得到的最干净的了。