file_download-dynamic-temp-file.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 os
  17. from decimal import Decimal, getcontext
  18. from tempfile import NamedTemporaryFile
  19. from taipy.gui import Gui, download
  20. # Initial precision
  21. precision = 10
  22. # Stores the path to the temporary file
  23. temp_path = None
  24. def pi(precision: int) -> list[int]:
  25. """Compute Pi to the required precision.
  26. Adapted from https://docs.python.org/3/library/decimal.html
  27. """
  28. saved_precision = getcontext().prec # Save precision
  29. getcontext().prec = precision
  30. three = Decimal(3) # substitute "three=3.0" for regular floats
  31. lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
  32. while s != lasts:
  33. lasts = s
  34. n, na = n + na, na + 8
  35. d, da = d + da, da + 32
  36. t = (t * n) / d
  37. s += t # type: ignore[assignment]
  38. digits = []
  39. while s != 0:
  40. integral = int(s)
  41. digits.append(integral)
  42. s = (s - integral) * 10
  43. getcontext().prec = saved_precision
  44. return digits
  45. # Remove the temporary file
  46. def clean_up(state):
  47. os.remove(state.temp_path)
  48. # Generate the digits, save them in a CSV temporary file, then trigger a download action
  49. # for that file.
  50. def download_pi(state):
  51. digits = pi(state.precision)
  52. with NamedTemporaryFile("r+t", suffix=".csv", delete=False) as temp_file:
  53. state.temp_path = temp_file.name
  54. temp_file.write("index,digit\n")
  55. for i, d in enumerate(digits):
  56. temp_file.write(f"{i},{d}\n")
  57. download(state, content=temp_file.name, name="pi.csv", on_action=clean_up)
  58. page = """
  59. # File Download - Dynamic content
  60. Precision:
  61. <|{precision}|slider|min=2|max=10000|>
  62. <|{None}|file_download|on_action=download_pi|label=Download Pi digits|>
  63. """
  64. Gui(page).run()