Skip to content Skip to sidebar Skip to footer

How To Serve Static File With A Hebrew Name In Python Bottle?

I receive a request from the client to download some file from the server. The filename is in Hebrew. @bottle.get('/download//') def download(fo

Solution 1:

Bottle is trying to set the Content-Disposition header on the HTTP response to attachment; filename=.... This doesn't work for non-ASCII characters, as Bottle handles HTTP headers with str internally... but then even if it didn't, there's no cross-browser-compatible way to set a Content-Disposition with a non-ASCII filename. (Background.)

You could set download='...' to a safe ASCII-only string to override Bottle's default guess (which is using the local filename, containing Unicode).

Alternatively, omit the download argument and rely on the browser guessing the filename from the end of the URL. (This is the only widely compatible way to get a Unicode download filename.) Unfortunately then Bottle will omit Content-Disposition completely, so consider altering the headers on the returned response to include plain Content-Disposition: attachment without a filename. Or perhaps you don't care, if the Content-Type is one that will always get downloaded anyway.

Solution 2:

In the last line try encoding the unicode string into binary using utf-8 codec:

return bottle.static_file(file_name.encode("utf-8"), root=folder_name.encode("utf-8"), download=True)

From the code you provided, it looks like the bottle.static_file method expects a string in binary format, therfore a default conversion using ascii codec is performed (as seen from the error message). As in your string you use Hebrew characters, which are not part of ascii, the default conversion fails. You need to use codec that supports national alphabets, like the utf-8.

For more information, see Unicode In Python, Completely Demystified

Solution 3:

send_file parameters must be unicode. Here is solution for bottle 0.5.8:

# -*- coding: utf-8 -*-from bottle import route, run, request, send_file, WSGIRefServer
@route('/:filename#.*#')defstatic_file(filename):
    send_file(filename.decode('utf-8'), root=ur'g:\Folder')
run(server=WSGIRefServer, host='192.168.1.5', port=80)  

Post a Comment for "How To Serve Static File With A Hebrew Name In Python Bottle?"