[英]How I can reuse aiohttp.ClientSession?
I am building own async python package and faced the problem.我正在构建自己的异步 python package 并遇到了问题。
This is my code:这是我的代码:
class Client:
"""
Async client for making requests
"""
def __init__(self, base_url: str = BASE_URL) -> None:
self.base_url = base_url
self.session = ClientSession()
async def get(self, method: str, *args: tp.Any, **kwargs: tp.Any) -> tp.Any:
async with self.session.get(f'{self.base_url}/{method}', *args, **kwargs) as response:
data = await response.json()
return data
When I try to use something like this:当我尝试使用这样的东西时:
await client.get()
I get我明白了
RuntimeError: Timeout context manager should be used inside a task
I suppose that the reason of this error is calling ClientSession()
not inside the coroutine.我想这个错误的原因是调用ClientSession()
不在协程内。 But I hope that somebody knows the way to re-use ClientSession()
但我希望有人知道重用ClientSession()
的方法
I have already read other similar questions, but they are not suitable to my situation.我已经阅读了其他类似的问题,但它们不适合我的情况。
You can initialize (and cache) the session when needed:您可以在需要时初始化(和缓存)session:
class Client:
"""
Async client for making requests
"""
def __init__(self, base_url: str = BASE_URL) -> None:
self.base_url = base_url
self.session = None
async def get(self, method: str, *args: tp.Any, **kwargs: tp.Any) -> tp.Any:
if not self.session:
self.session = ClientSession()
async with self.session.get(f'{self.base_url}/{method}', *args, **kwargs) as response:
data = await response.json()
return data
Depending on how you use the Client
you can also use a class attribute for the session object.根据您使用Client
的方式,您还可以为 session object 使用class属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.