core: add async context manager support

parent 8574c6eb
...@@ -27,14 +27,10 @@ from altrepo import ALTRepo ...@@ -27,14 +27,10 @@ from altrepo import ALTRepo
from altrepo.api.types import Branch from altrepo.api.types import Branch
async def main(): async def main():
client = ALTRepo() async with ALTRepo() as client:
await client.init() result = await client.api.package.package_info("firefox", branch=Branch.sisyphus)
pkg = result.packages[0]
result = await client.api.package.package_info("firefox", branch=Branch.sisyphus) print(f"{pkg.name} {pkg.version}-{pkg.release}")
pkg = result.packages[0]
print(f"{pkg.name} {pkg.version}-{pkg.release}")
await client.close()
asyncio.run(main()) asyncio.run(main())
``` ```
...@@ -170,14 +166,11 @@ config = ALTRepoConfig( ...@@ -170,14 +166,11 @@ config = ALTRepoConfig(
client = ALTRepo(config=config) client = ALTRepo(config=config)
``` ```
Если в вашем приложении уже есть `aiohttp.ClientSession`, её можно передать при инициализации, чтобы не создавать лишних соединений: Если в вашем приложении уже есть `aiohttp.ClientSession`, её можно передать при инициализации:
```python ```python
import aiohttp
session = aiohttp.ClientSession()
client = ALTRepo() client = ALTRepo()
await client.init(session=session) await client.init(session=existing_session)
``` ```
## Лицензия ## Лицензия
......
...@@ -28,5 +28,12 @@ class ALTRepo: ...@@ -28,5 +28,12 @@ class ALTRepo:
async def close(self): async def close(self):
await self._session.close() await self._session.close()
async def __aenter__(self):
await self.init()
return self
async def __aexit__(self, *args):
await self.close()
__all__ = ("ALTRepo", "ALTRepoConfig") __all__ = ("ALTRepo", "ALTRepoConfig")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment