Skip to content

Commit 4bf26d9

Browse files
committed
Improve
1 parent 71a6275 commit 4bf26d9

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

plugwise_usb/helpers/cache.py

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -109,11 +109,13 @@ async def write_cache(self, data: dict[str, str], rewrite: bool = False) -> None
109109
data_to_write.append(f"{_key}{CACHE_KEY_SEPARATOR}{_value}\n")
110110

111111
# Atomic write using aiofiles with temporary file
112-
if self._cache_file is not None:
113-
cache_file_path = Path(self._cache_file)
114-
temp_path = cache_file_path.with_name(
115-
f".{cache_file_path.name}.tmp.{os_getpid()}"
116-
)
112+
if self._cache_file is None:
113+
raise CacheError("Unable to save cache, cache-file has no name")
114+
115+
cache_file_path = Path(self._cache_file)
116+
temp_path = cache_file_path.with_name(
117+
f".{cache_file_path.name}.tmp.{os_getpid()}"
118+
)
117119

118120
try:
119121
# Write to temporary file using aiofiles
@@ -160,27 +162,30 @@ async def read_cache(self) -> dict[str, str]:
160162
f"Unable to save cache. Initialize cache file '{self._file_name}' first."
161163
)
162164
current_data: dict[str, str] = {}
165+
if self._cache_file is None:
166+
_LOGGER.debug("Cache file has no name, return empty cache data")
167+
return current_data
168+
163169
if not self._cache_file_exists:
164170
_LOGGER.debug(
165171
"Cache file '%s' does not exists, return empty cache data",
166172
self._cache_file,
167173
)
168174
return current_data
169175

170-
if self._cache_file is not None:
171-
try:
172-
async with aiofiles_open(
173-
file=self._cache_file,
174-
encoding=UTF8,
175-
) as read_file_data:
176-
lines: list[str] = await read_file_data.readlines()
177-
except OSError as exc:
178-
# suppress file errors as this is expected the first time
179-
# when no cache file exists yet.
180-
_LOGGER.warning(
181-
"OS error %s while reading cache file %s", exc, str(self._cache_file)
182-
)
183-
return current_data
176+
try:
177+
async with aiofiles_open(
178+
file=self._cache_file,
179+
encoding=UTF8,
180+
) as read_file_data:
181+
lines: list[str] = await read_file_data.readlines()
182+
except OSError as exc:
183+
# suppress file errors as this is expected the first time
184+
# when no cache file exists yet.
185+
_LOGGER.warning(
186+
"OS error %s while reading cache file %s", exc, str(self._cache_file)
187+
)
188+
return current_data
184189

185190
for line in lines:
186191
data = line.strip()

0 commit comments

Comments
 (0)