1
0

file_download_dynamic.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 io
  17. from decimal import Decimal, getcontext
  18. from taipy.gui import Gui, download
  19. def pi(precision: int) -> list[int]:
  20. """Compute Pi to the required precision.
  21. Adapted from https://docs.python.org/3/library/decimal.html
  22. """
  23. saved_precision = getcontext().prec # Save precision
  24. getcontext().prec = precision
  25. three = Decimal(3) # substitute "three=3.0" for regular floats
  26. lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
  27. while s != lasts:
  28. lasts = s
  29. n, na = n + na, na + 8
  30. d, da = d + da, da + 32
  31. t = (t * n) / d
  32. s += t # type: ignore[assignment]
  33. digits = []
  34. while s != 0:
  35. integral = int(s)
  36. digits.append(integral)
  37. s = (s - integral) * 10
  38. getcontext().prec = saved_precision
  39. return digits
  40. # Generate the digits, save them in a CSV file content, and trigger a download action
  41. # so the user can retrieve them
  42. def download_pi(state):
  43. digits = pi(state.precision)
  44. buffer = io.StringIO()
  45. buffer.write("index,digit\n")
  46. for i, d in enumerate(digits):
  47. buffer.write(f"{i},{d}\n")
  48. download(state, content=bytes(buffer.getvalue(), "UTF-8"), name="pi.csv")
  49. # Initial precision
  50. precision = 10
  51. page = """
  52. Precision:
  53. <|{precision}|slider|min=2|max=10000|>
  54. <|{None}|file_download|on_action=download_pi|label=Download Pi digits|>
  55. """
  56. if __name__ == "__main__":
  57. Gui(page).run(title="File Download - Dynamic content")