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

broadcast callback on non shared variables #1441

Merged
merged 24 commits into from
Jul 1, 2024
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
24 changes: 9 additions & 15 deletions doc/gui/examples/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@
# -----------------------------------------------------------------------------------------
# Demonstrate how to share variable values across multiple clients.
# This application creates a thread that increments a value every few seconds.
# The value is updated for every client using the state.broadcast() method.
# The text of the button that starts or stops the thread is updated on every client's browser
# using a direct assignment of the state property because the variable is declared 'shared'.
# The value is updated for every client in a function invoked by Gui.broadcast_change().
# The text of the button that starts or stops the thread is updated using the
# State.assign() method, and udateds on every client's browser because the variable was
# declared 'shared' by calling Gui.add_shared_variable().
# -----------------------------------------------------------------------------------------
from threading import Event, Thread
from time import sleep

from taipy.gui import Gui, State, broadcast_callback
from taipy.gui import Gui, State

counter = 0

Expand All @@ -35,22 +36,16 @@
button_text = button_texts[0]


# Invoked by the timer
def update_counter(state: State, c):
# Update all clients
state.broadcast("counter", c)


def count(event, gui):
while not event.is_set():
global counter
counter = counter + 1
broadcast_callback(gui, update_counter, [counter])
gui.broadcast_change("counter", counter)
sleep(2)


# Start or stop the timer when the button is pressed
def start_or_stop(state):
def start_or_stop(state: State):
global thread
if thread: # Timer is running
thread_event.set()
Expand All @@ -59,9 +54,8 @@ def start_or_stop(state):
thread_event.clear()
thread = Thread(target=count, args=[thread_event, state.get_gui()])
thread.start()
# Update button status.
# Because "button_text" is shared, all clients are updated
state.button_text = button_texts[1 if thread else 0]
# Update button status for all states.
state.assign("button_text", button_texts[1 if thread else 0])


page = """# Broadcasting values
Expand Down
57 changes: 57 additions & 0 deletions doc/gui/examples/broadcast_callback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
# python <script>
# -----------------------------------------------------------------------------------------
# Demonstrate how to update the value of a variable across multiple clients.
# This application creates a thread that sets a variable to the current time.
# The value is updated for every client when Gui.broadcast_change() is invoked.
# -----------------------------------------------------------------------------------------
from datetime import datetime
from threading import Thread
from time import sleep

from taipy.gui import Gui

current_time = datetime.now()
update = False


# Update the 'current_time' state variable if 'update' is True
def update_state(state, updated_time):
if state.update:
state.current_time = updated_time


# The function that executes in its own thread.
# Call 'update_state()` every second.
def update_time(gui):
while True:
gui.broadcast_callback(update_state, [datetime.now()])
sleep(1)


page = """
Current time is: <|{current_time}|format=HH:mm:ss|>

Update: <|{update}|toggle|>
"""

gui = Gui(page)

# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()

gui.run()
48 changes: 48 additions & 0 deletions doc/gui/examples/broadcast_change.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# Copyright 2021-2024 Avaiga Private Limited
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
# an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# -----------------------------------------------------------------------------------------
# To execute this script, make sure that the taipy-gui package is installed in your
# Python environment and run:
# python <script>
# -----------------------------------------------------------------------------------------
# Demonstrate how to invoke a callback for different clients.
# This application creates a thread that, every second, invokes a callback for every client
# so the current time may be updated, under a state-dependant condition.
# -----------------------------------------------------------------------------------------
from datetime import datetime
from threading import Thread
from time import sleep

from taipy.gui import Gui

current_time = datetime.now()


# The function that executes in its own thread.
# Update the current time every second.
def update_time(gui):
while True:
gui.broadcast_change("current_time", datetime.now())
sleep(1)


page = """
Current time is: <|{current_time}|format=HH:mm:ss|>
"""

gui = Gui(page)

# Run thread that regularly updates the current time
thread = Thread(target=update_time, args=[gui], name="clock")
thread.daemon = True
thread.start()

gui.run()
2 changes: 1 addition & 1 deletion frontend/taipy-gui/src/components/Taipy/PaginatedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ const PaginatedTable = (props: TaipyPaginatedTableProps) => {
}
return [colsOrder, baseColumns, styTt.styles, styTt.tooltips, hNan, filter];
} catch (e) {
console.info("PTable.columns: " + ((e as Error).message || e));
console.info("PaginatedTable.columns: ", (e as Error).message || e);
}
}
return [
Expand Down
14 changes: 2 additions & 12 deletions frontend/taipy-gui/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,23 +170,13 @@ export const formatWSValue = (
if (value == "") {
return "";
}
try {
return getDateTimeString(value.toString(), dataFormat, formatConf);
} catch (e) {
console.error(`wrong dateformat "${dataFormat || formatConf.dateTime}"`, e);
}
return getDateTimeString(value.toString(), undefined, formatConf);
return getDateTimeString(value.toString(), dataFormat, formatConf);
case "datetime.date":
case "date":
if (value == "") {
return "";
}
try {
return getDateTimeString(value.toString(), dataFormat, formatConf, undefined, false);
} catch (e) {
console.error(`wrong dateformat "${dataFormat || formatConf.date}"`, e);
}
return getDateTimeString(value.toString(), undefined, formatConf, undefined, false);
return getDateTimeString(value.toString(), dataFormat, formatConf, undefined, false);
case "int":
case "float":
case "number":
Expand Down
10 changes: 5 additions & 5 deletions taipy/config/common/_template_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,15 @@ def _replace_template(cls, template, type, required, default):
if required:
raise MissingEnvVariableError(f"Environment variable {var} is not set.")
return default
if type == bool:
if type is bool:
return cls._to_bool(val)
elif type == int:
elif type is int:
return cls._to_int(val)
elif type == float:
elif type is float:
return cls._to_float(val)
elif type == Scope:
elif type is Scope:
return cls._to_scope(val)
elif type == Frequency:
elif type is Frequency:
return cls._to_frequency(val)
else:
if dynamic_type == "bool":
Expand Down
4 changes: 2 additions & 2 deletions taipy/gui/data/array_dict_data_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ def _get_dataframe(self, value: t.Any) -> t.Union[t.List[pd.DataFrame], pd.DataF
types = {type(x) for x in value}
if len(types) == 1:
type_elt = next(iter(types), None)
if type_elt == list:
if type_elt is list:
lengths = {len(x) for x in value}
return (
pd.DataFrame(value)
if len(lengths) == 1
else [pd.DataFrame({f"{i}/0": v}) for i, v in enumerate(value)]
)
elif type_elt == dict:
elif type_elt is dict:
return [pd.DataFrame(v) for v in value]
elif type_elt == _MapDict:
return [pd.DataFrame(v._dict) for v in value]
Expand Down
Loading
Loading