-
-
Notifications
You must be signed in to change notification settings - Fork 629
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
extracted classes from storage.py and first minimal Redis sync for ap…
…p.storage.general
- Loading branch information
Showing
10 changed files
with
136 additions
and
65 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
from pathlib import Path | ||
from typing import Optional | ||
|
||
import aiofiles | ||
|
||
from nicegui import background_tasks, core, json, observables | ||
from nicegui.logging import log | ||
|
||
|
||
class PersistentDict(observables.ObservableDict): | ||
|
||
def __init__(self, filepath: Path, encoding: Optional[str] = None, *, indent: bool = False) -> None: | ||
self.filepath = filepath | ||
self.encoding = encoding | ||
self.indent = indent | ||
try: | ||
data = json.loads(filepath.read_text(encoding)) if filepath.exists() else {} | ||
except Exception: | ||
log.warning(f'Could not load storage file {filepath}') | ||
data = {} | ||
super().__init__(data, on_change=self.backup) | ||
|
||
def backup(self) -> None: | ||
"""Back up the data to the given file path.""" | ||
if not self.filepath.exists(): | ||
if not self: | ||
return | ||
self.filepath.parent.mkdir(exist_ok=True) | ||
|
||
async def backup() -> None: | ||
async with aiofiles.open(self.filepath, 'w', encoding=self.encoding) as f: | ||
await f.write(json.dumps(self, indent=self.indent)) | ||
if core.loop: | ||
background_tasks.create_lazy(backup(), name=self.filepath.stem) | ||
else: | ||
core.app.on_startup(backup()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from collections.abc import MutableMapping | ||
from typing import Any, Dict, Iterator | ||
|
||
|
||
class ReadOnlyDict(MutableMapping): | ||
|
||
def __init__(self, data: Dict[Any, Any], write_error_message: str = 'Read-only dict') -> None: | ||
self._data: Dict[Any, Any] = data | ||
self._write_error_message: str = write_error_message | ||
|
||
def __getitem__(self, item: Any) -> Any: | ||
return self._data[item] | ||
|
||
def __setitem__(self, key: Any, value: Any) -> None: | ||
raise TypeError(self._write_error_message) | ||
|
||
def __delitem__(self, key: Any) -> None: | ||
raise TypeError(self._write_error_message) | ||
|
||
def __iter__(self) -> Iterator: | ||
return iter(self._data) | ||
|
||
def __len__(self) -> int: | ||
return len(self._data) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import redis.asyncio as redis | ||
|
||
from nicegui import background_tasks, core, json, observables | ||
from nicegui.logging import log | ||
|
||
|
||
class RedisDict(observables.ObservableDict): | ||
|
||
def __init__(self, redis_url: str = 'redis://localhost:6379', key_prefix: str = 'nicegui:', encoding: str = 'utf-8') -> None: | ||
self.redis_client = redis.from_url(redis_url) | ||
self.pubsub = self.redis_client.pubsub() | ||
self.key_prefix = key_prefix | ||
self.encoding = encoding | ||
|
||
# Initialize with empty data first | ||
super().__init__({}, on_change=self.backup) | ||
|
||
async def initialize(self) -> None: | ||
"""Load initial data from Redis and start listening for changes.""" | ||
try: | ||
data = await self._load_data() | ||
self.update(data) | ||
except Exception: | ||
log.warning(f'Could not load data from Redis with prefix {self.key_prefix}') | ||
|
||
await self._listen_for_changes() | ||
|
||
async def _load_data(self) -> dict: | ||
data = await self.redis_client.get(self.key_prefix + 'data') | ||
return json.loads(data) if data else {} | ||
|
||
async def _listen_for_changes(self) -> None: | ||
await self.pubsub.subscribe(self.key_prefix + 'changes') | ||
async for message in self.pubsub.listen(): | ||
if message['type'] == 'message': | ||
new_data = json.loads(message['data']) | ||
if new_data != self: | ||
self.update(new_data) | ||
|
||
def backup(self) -> None: | ||
"""Back up the data to Redis and notify other instances.""" | ||
async def backup() -> None: | ||
pipeline = self.redis_client.pipeline() | ||
pipeline.set(self.key_prefix + 'data', json.dumps(self)) | ||
pipeline.publish(self.key_prefix + 'changes', json.dumps(self)) | ||
await pipeline.execute() | ||
if core.loop: | ||
background_tasks.create_lazy(backup(), name=f'redis-{self.key_prefix}') | ||
else: | ||
core.app.on_startup(backup()) | ||
|
||
async def close(self) -> None: | ||
"""Close Redis connection and subscription.""" | ||
await self.pubsub.unsubscribe() | ||
await self.pubsub.close() | ||
await self.redis_client.close() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters