python - 装饰的异步方法返回 None
问题描述
我有以下类 Yodel 从官方 Yodel API 获取数据。为了让它更快,我使用 aiohttp 和 asyncio 但我想让它在用户实例化对象并调用它的方法时看起来同步。为此,我创建了一个装饰器以使其可以tracking
作为同步方法进行调用。
import aiohttp
import asyncio
import time
class Yodel:
API_BASE_URL = "api.yodel.co.uk"
CLIENT_ID = "..."
CLIENT_SECRET = "..."
def __init__(self):
self.loop = asyncio.get_event_loop()
self.loop.run_until_complete(self.auth())
async def auth(self):
self.session = aiohttp.ClientSession()
url = f"https://{Yodel.API_BASE_URL}/tracking/v1.0/oauth2/token"
payload = f"grant_type=client_credentials&client_id={Yodel.CLIENT_ID}&client_secret={Yodel.CLIENT_SECRET}&scope=tracking"
headers = {
"Accept": "application/json",
"content-type": "application/x-www-form-urlencoded"
}
response = await self.session.request("POST", url=url, data=payload, headers=headers)
response = await response.json()
self.session = aiohttp.ClientSession(
headers = {
"Accept": "*/*",
"Authorization": f"Bearer {response['access_token']}",
"x-ibm-client-id": Yodel.CLIENT_ID,
}
)
async def fetch_data(self, url, **kwargs):
response = await self.session.request("GET", url=url, **kwargs)
response = await response.json()
return response
def async_loop(f):
def decorated(self, *args, **kwargs):
self.loop.run_until_complete(f(self, *args, **kwargs))
return decorated
@async_loop
async def tracking(self, trackingIds: list, **kwargs):
tasks = []
for trackingId in trackingIds:
endpoint = f"/tracking/v1.0/parcel-tracking/{trackingId}"
url = f"https://{Yodel.API_BASE_URL}{endpoint}"
tasks.append(self.fetch_data(url, **kwargs))
trackings = await asyncio.gather(*tasks, return_exceptions=True)
# I see trackings as json when inspecting variables, however...
return trackings # Returns None
if __name__ == "__main__":
yodel = Yodel()
trackings = yodel.tracking([
"JJD0002247772000106",
"JJD0002247772000107",
"JJD0002247772000108"
])
退货
None
解决方案
哦,它只是失踪了
def async_loop(f):
def decorated(self, *args, **kwargs):
response = self.loop.run_until_complete(f(self, *args, **kwargs))
return response
return decorated
推荐阅读
- sql - TSQL:如何格式化时间:'0.729166667' 像 Excel 一样:'5:30:00 pm'
- firebase - 为什么在 Github Actions 中分离作业而不是添加步骤?
- python - 在 python 生成器函数中有条件
- https - 向受保护的 GitLab 页面发出 HTTPS 请求
- azure - 如何在 azure Release 管道中使用 Linux 代理运行 vstest?
- python - 如何在python中获取与同一项目相关但在不同日期的行并使用第一个和最后一个日期的值创建列?
- angular - 从服务中获取模拟值的问题,该服务返回组件中的可观察值
- python - 多数据的 MLP 训练
- sympy - 包含复指数的多项式的 factor_list 中的错误
- mysql - 如何从存储库中导出 Workbench 中的 mysql 数据库