Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
rodja committed Dec 8, 2024
1 parent 7aff68d commit c98a79d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 16 deletions.
2 changes: 1 addition & 1 deletion nicegui/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, **kwargs) -> None:
self.config = AppConfig()

self._startup_handlers: List[Union[Callable[..., Any], Awaitable]] = [self.storage.general.initialize,]
self._shutdown_handlers: List[Union[Callable[..., Any], Awaitable]] = []
self._shutdown_handlers: List[Union[Callable[..., Any], Awaitable]] = [self.storage.general.close]
self._connect_handlers: List[Union[Callable[..., Any], Awaitable]] = []
self._disconnect_handlers: List[Union[Callable[..., Any], Awaitable]] = []
self._exception_handlers: List[Callable[..., Any]] = [log.exception]
Expand Down
20 changes: 5 additions & 15 deletions nicegui/persistence/redis_persistent_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,34 +11,24 @@ def __init__(self, redis_url: str = 'redis://localhost:6379', key_prefix: str =
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)
super().__init__({}, on_change=self.publish)

async def initialize(self) -> None:
"""Load initial data from Redis and start listening for changes."""
try:
data = await self._load_data()
self.update(data)
data = await self.redis_client.get(self.key_prefix + 'data')
self.update(json.loads(data) if data else {})
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."""
def publish(self) -> None:
"""Publish 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))
Expand Down

0 comments on commit c98a79d

Please sign in to comment.