main.py 838 B

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