Skip to content

Commit

Permalink
Merge pull request #567 from TeskaLabs/feature/library-open
Browse files Browse the repository at this point in the history
Library: introduce context manager to ensure itemio is closed
  • Loading branch information
ateska committed Apr 15, 2024
2 parents c68f127 + bd6ef9d commit 0aa6ab2
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion asab/library/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import tempfile
import functools
import configparser
import contextlib

import yaml

Expand Down Expand Up @@ -207,7 +208,7 @@ async def read(self, path: str, tenant: typing.Optional[str] = None) -> typing.O
Returns:
( IO | None ): Readable stream with the content of the library item. `None` is returned if the item is not found or if it is disabled (either globally or for the specified tenant).
Examples:
Example:
```python
itemio = await library.read('/path', 'tenant')
Expand All @@ -232,6 +233,34 @@ async def read(self, path: str, tenant: typing.Optional[str] = None) -> typing.O

return None


@contextlib.asynccontextmanager
async def open(self, path: str, tenant: typing.Optional[str] = None):
"""
Read the content of the library item specified by `path` in a SAFE way, protected by a context manager/with statement.
This method can be used only after the Library is ready.
Example:
```python
async with self.App.LibraryService.open(path) as b:
if b is None:
return None
text = b.read().decode("utf-8")
```
"""

itemio = await self.read(path, tenant)
if itemio is None:
yield itemio
else:
try:
yield itemio
finally:
itemio.close()


async def list(self, path: str = "/", tenant: typing.Optional[str] = None, recursive: bool = False) -> typing.List[LibraryItem]:
"""
List the directory of the library specified by the path that are enabled for the specified tenant. This method can be used only after the Library is ready.
Expand Down

0 comments on commit 0aa6ab2

Please sign in to comment.