1
0

table_guard_edits.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. import random
  17. import requests
  18. from taipy.gui import Gui, State, notify
  19. # The RandomAPI API used to generate random user names
  20. randomuser_url = "https://randomuser.me/api"
  21. # Create a random person name and salary
  22. def pick_user() -> tuple[str, int]:
  23. # Call the Random User Generator API to create a random person name
  24. response = requests.get(randomuser_url)
  25. # If the request was successful
  26. if response.status_code == 200:
  27. # Make a new name and
  28. try:
  29. person = response.json()["results"][0]
  30. name = person["name"]
  31. new_user = f"{name['first']} {name['last']}"
  32. # Generate a random salary expectation amount
  33. salary = random.randint(8, 24) * 5000
  34. return (new_user, salary)
  35. except ValueError:
  36. # There was a back-end error
  37. print("ERROR: Invoking the Random User Generator API") # noqa: F401, T201
  38. return ("ERROR", 0)
  39. # The API cannot be reached
  40. print("ERROR: Could not invoke the Random User Generator API") # noqa: F401, T201
  41. return ("ERROR", 0)
  42. # Generate four random persons with their salary expectation and store them in a dictionary
  43. candidates: dict[str, list] = {"Name": [], "Salary": []}
  44. for candidate in [pick_user() for _ in range(4)]:
  45. candidates["Name"].append(candidate[0])
  46. candidates["Salary"].append(candidate[1])
  47. # Triggered when the user clicks the 'Delete' icon and validates
  48. def check_delete(state: State, var_name: str, payload: dict):
  49. # How many candidates are there in the list? (i.e. how many rows in the table)
  50. n_candidates = len(state.candidates["Name"])
  51. # Check if a candidate can be removed from the list
  52. if n_candidates <= 3:
  53. # Notify the user that the minimum limit has been reached
  54. notify(state, "E", "Too few candidates")
  55. else:
  56. # Remove the row from the table
  57. state.get_gui().table_on_delete(state, var_name, payload)
  58. # Triggered when the user clicks the 'Add' icon and validates
  59. def check_add(state: State, var_name: str, payload: dict):
  60. # How many candidates are there in the list? (i.e. how many rows in the table)
  61. n_candidates = len(state.candidates["Name"])
  62. # Check if a new candidate can be added to the list
  63. if n_candidates >= 6:
  64. # Notify the user that the maximum limit has been reached
  65. notify(state, "E", "Too many candidates")
  66. else:
  67. # Create new candidate
  68. new_row = pick_user()
  69. # Add new row at the end of the list
  70. payload["index"] = n_candidates
  71. # Add the new candidate as a row in the table
  72. state.get_gui().table_on_add(state, var_name, payload, new_row=list(new_row))
  73. # Triggered when the user changes the value of a cell
  74. # Force the user-entered value to be a multiple of 5000
  75. def force_salary(state: State, var_name: str, payload: dict):
  76. # Get the salary proposal from the callback's payload
  77. proposed_salary = payload["value"]
  78. # Round it the the nearest multiple of 5000
  79. proposed_salary = round(proposed_salary / 500) * 500
  80. # Set it as the value to be stored in the dataset
  81. payload["value"] = proposed_salary
  82. state.get_gui().table_on_edit(state, var_name, payload)
  83. page = "<|{candidates}|table|on_delete=check_delete|on_add=check_add|editable[Salary]|on_edit=force_salary|show_all|>"
  84. if __name__ == "__main__":
  85. Gui(page).run(title="Table - Guard edits")