2

I want to return .txt with some results to user by particular route. so i have:

@route('/export')
def export_results():
    #here is some data gathering ot the variable
    return #here i want to somehow return on-the-fly my variable as a .txt file

So, I know how to:

  • open, return static_file(root='blahroot',filename='blah'), close, unlink
  • make some similar actions with 'import tempfile' and so on

BUT: I heard that i can somehow set response http headers in some particular way, that returning my variable as a text will be got by browsers like a file.

the question is: how to make it run this way?

P.S.: as shown in tags I am on Python3, using Bottle and plan to have server from cherrypy as wsgi server

Amphyby
  • 73
  • 1
  • 11

1 Answers1

2

If I understand correctly, you want your visitor's browser to offer to save the response as a file, rather than displaying it in the browser itself. To do that is simple; just set these headers:

Content-Type: text/plain
Content-Disposition: attachment; filename="yourfilename.txt"

and the browser will prompt the user to save the file and will suggest file name "yourfilename.txt". (More discussion here.)

To set the headers in Bottle, use response.set_header:

from bottle import response

@route('/export')
def export():
    the_text = <however you choose to get the text of your response>
    response.set_header('Content-Type', 'text/plain')
    response.set_header('Content-Disposition', 'attachment; filename="yourfilename.txt"')
    return the_text
Community
  • 1
  • 1
ron rothman
  • 17,348
  • 7
  • 41
  • 43