Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using StaticFileHandler to host a file on Tornado Python

Hi I am attempting to use StaticFileHandler in Tornado and for the most part its working, except its outputting the file (.csv) in a webpage when I click download. The only way I can save the file is Right clicking and saying save target as (but this doesn't work in all browsers).

How can I force the file to be downloaded? I know I need to somehow set the header of the StaticFileHandler like this:

    self.set_header('Content-Type','text-csv')
    self.set_header('Content-Disposition','attachment')

But I have no idea how to set it because it is a default handler.

Thanks for your time!

like image 909
Nick Trileski Avatar asked Jan 28 '26 20:01

Nick Trileski


2 Answers

Extend the web.StaticFileHandler

class StaticFileHandler(web.StaticFileHandler):
    def get(self, path, include_body=True):
        if [some csv check]:
            # your code from above, or anything else custom you want to do
            self.set_header('Content-Type','text-csv')  
            self.set_header('Content-Disposition','attachment')

        super(StaticFileHandler, self).get(path, include_body)

Dont forget to use your extended class in the handler!

like image 58
Sasha Avatar answered Jan 31 '26 10:01

Sasha


Since comments are liable to be deleted, the correct solution (as described in the comment by Jan) is:

[T]he documentation of web.StaticFileHandler explicitly discourages to overwrite the get method. The classmethod 'set_extra_headers(path)' is supported and can be used instead.

The correct solution would look like this:

class StaticFileHandler(web.StaticFileHandler):
    @classmethod
    def set_extra_headers(self, path):
        if path.endswith('.csv'):
            self.set_header('Content-Type', 'text-csv')  
            self.set_header('Content-Disposition', 'attachment')
like image 29
shadowtalker Avatar answered Jan 31 '26 08:01

shadowtalker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!