Skip to content Skip to sidebar Skip to footer

How To Export CSV To Absolute Path In Flask, Using Content-disposition?

I have the following code in Flask app: @app.route('/transform', methods=['POST']) def transform_view(): //other irrelevant codes resp = make_response(data1.to_csv()) r

Solution 1:

This isn't really answering your exception/unicode error, but some advice regarding the use of Content-Disposition...

The attachment directive isn't meant to include a full path. See MDN docs:

The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. This parameter provides mostly indicative information. When used in combination with Content-Disposition: attachment, it is used as the default filename for an eventual "Save As" dialog presented to the user.

So when you mention:

export.csv is downloaded in Downloads folder. But I want to export it to the directory where my project resides, which is C:\Users\Admin\Desktop\crap9\flask

Selection of the Downloads folder is because your browser config has this as the default Save As location. This can't be tweaked via a header from your server. If you really want to save that to your the server's filesystem, it may be advisable to do this with a standard python method. Something like:

with open('export.csv', 'wb') as f:
    f.write(data1.to_csv())

I think you may be confusing the server's filesystem with the client filesystem, because you're running the app locally at this stage. When deployed these are two completely separate things. That full path will not exist on the client filesystm and your transform_view function, which makes the file downloadable to the end user, cannot dictate which directory this will be saved to once downloaded by the browser.

So probably wise to make the decision of whether to actually save to the server's filesystem, or make the file downloadable where the client gets to pick the save location (you can still set the filename itself).


Post a Comment for "How To Export CSV To Absolute Path In Flask, Using Content-disposition?"