1
0

async_callback.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. # -----------------------------------------------------------------------------------------
  12. # To execute this script, make sure that the taipy-gui package is installed in your
  13. # Python environment and run:
  14. # python <script>
  15. # -----------------------------------------------------------------------------------------
  16. # Demonstrate how to update the value of a variable across multiple clients.
  17. # This application creates a thread that sets a variable to the current time.
  18. # The value is updated for every client when Gui.broadcast_change() is invoked.
  19. # -----------------------------------------------------------------------------------------
  20. import asyncio
  21. import taipy.gui.builder as tgb
  22. from taipy.gui import Gui, State
  23. # This callback is invoked inside a separate thread
  24. # it can access the state but cannot return a value
  25. async def heavy_function(state: State):
  26. state.logs = "Starting...\n"
  27. state.logs += "Searching documents\n"
  28. await asyncio.sleep(5)
  29. state.logs += "Responding to user\n"
  30. await asyncio.sleep(5)
  31. state.logs += "Fact Checking\n"
  32. await asyncio.sleep(5)
  33. state.result = "Done!"
  34. logs = ""
  35. result = "No response yet"
  36. with tgb.Page() as main_page:
  37. # the async callback is used as any other callback
  38. tgb.button("Respond", on_action=heavy_function)
  39. with tgb.part("card"):
  40. tgb.text("{logs}", mode="pre")
  41. tgb.text("# Result", mode="md")
  42. tgb.text("{result}")
  43. if __name__ == "__main__":
  44. Gui(main_page).run(title="Async - Callback")