Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use rx.background, rx.cached_var, and rx.Cookie in the clock example #147

Merged
merged 6 commits into from
Oct 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 33 additions & 11 deletions clock/clock/clock.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""A Reflex example of a analog clock."""

import asyncio
from datetime import datetime
from datetime import datetime, timezone
from typing import Any

import reflex as rx
Expand All @@ -18,6 +18,7 @@
"US/Pacific",
"US/Eastern",
]
DEFAULT_ZONE = TIMEZONES[-2]


def rotate(degrees: int) -> str:
Expand All @@ -36,12 +37,28 @@ class State(rx.State):
"""The app state."""

# The time zone to display the clock in.
zone: str = "US/Pacific"
zone: str = rx.Cookie(DEFAULT_ZONE)

# Whether the clock is running.
running: bool = False

@rx.var
# The last updated timestamp
_now: datetime = datetime.fromtimestamp(0)

@rx.cached_var
def valid_zone(self) -> str:
"""Get the current time zone.

Returns:
The current time zone.
"""
try:
pytz.timezone(self.zone)
except Exception:
return DEFAULT_ZONE
return self.zone

@rx.cached_var
def time_info(self) -> dict[str, Any]:
"""Get the current time info.

Expand All @@ -50,7 +67,7 @@ def time_info(self) -> dict[str, Any]:
Returns:
A dictionary of the current time info.
"""
now = datetime.now(pytz.timezone(self.zone))
now = self._now.astimezone(pytz.timezone(self.valid_zone))
return {
"hour": now.hour if now.hour <= 12 else now.hour % 12,
"minute": now.minute,
Expand All @@ -66,16 +83,21 @@ def time_info(self) -> dict[str, Any]:
def on_load(self):
"""Switch the clock off when the page refreshes."""
self.running = False
self.zone = "US/Pacific"
self.refresh()

def refresh(self):
"""Refresh the clock."""
self._now = datetime.now(timezone.utc)

@rx.background
async def tick(self):
"""Update the clock every second."""
# Sleep for a second.
await asyncio.sleep(1)
while self.running:
async with self:
self.refresh()

# If the clock is running, tick again.
if self.running:
return State.tick
# Sleep for a second.
await asyncio.sleep(1)

def flip_switch(self, running: bool):
"""Start or stop the clock.
Expand Down Expand Up @@ -161,7 +183,7 @@ def timezone_select() -> rx.Component:
TIMEZONES,
placeholder="Select a time zone.",
on_change=State.set_zone,
value=State.zone,
value=State.valid_zone,
bg="#white",
)

Expand Down