main.py 891 B

1234567891011121314151617181920212223242526272829
  1. #!/usr/bin/env python3
  2. from io import StringIO
  3. from uuid import uuid4
  4. from fastapi.responses import StreamingResponse
  5. from nicegui import Client, app, ui
  6. @ui.page('/')
  7. async def index(client: Client):
  8. download_path = f"/download/{uuid4()}.txt"
  9. @app.get(download_path)
  10. async def download():
  11. # create a file-like object from the string
  12. string_io = StringIO(text_entry.value)
  13. return StreamingResponse(
  14. string_io, media_type="text/plain",
  15. headers={'Content-Disposition': 'attachment; filename=download.txt', }
  16. )
  17. text_entry = ui.textarea(value="hello world")
  18. ui.button("Download", on_click=lambda: ui.download(download_path))
  19. # cleanup the download route after the client disconnected
  20. await client.disconnected()
  21. app.routes[:] = [route for route in app.routes if route.path != download_path]
  22. ui.run()