【发布时间】:2021-05-15 00:10:58
【问题描述】:
所以在aiohttp 建议重用ClientSession 以避免开销。
所以说我有这样的事情:
async def get_id_from_url(session, url):
async with session.get(url) as response:
return (await response.json())['id'] if response.ok else ''
async def get_ids(urls: List[str]):
async with aiohttp.ClientSession() as session:
ids = await asyncio.gather(*[get_id_from_url(session, url) for url in urls])
print(ids)
我想缓存 get_id_from_url 函数,我查看了许多与缓存异步函数有关的问题/包:aiocache
还有这个answer。
但是有一个问题,我不希望缓存依赖于session参数,我只希望它依赖于url参数。
我该怎么做?
【问题讨论】:
-
而不是使用装饰器
@cached,您可以在函数内部使用cache,并仅使用url-cache.set(url, result)和if url in cache: return cache.get(url)保留结果
标签: python asynchronous caching aiohttp