如何在python瓶中使用希伯来语名称提供静态文件?
我收到客户端的请求,要求从服务器下载一些文件。
文件名使用希伯来语。
I receive a request from the client to download some file from the server. The filename is in Hebrew.
@bottle.get("/download/<folder_name>/<file_name>")
def download(folder_name, file_name):
file_name = file_name.decode('utf-8')
folder_name = folder_name.decode('utf-8')
if os.path.exists(os.path.join(folder_name, file_name)):
return bottle.static_file(file_name, root=folder_name, download=True)
最后一行失败:
return bottle.static_file(file_name, root=folder_name, download=True)
我遇到异常:
UnicodeEncodeError: 'ascii' codec can't encode characters in position 22-25: ordinal not in range(128)
我不知道我在这里做错了什么。
I have no idea what am i doing wrong here.
Callstack显示异常源自python瓶代码:
Callstack shows the exception derives from python bottle code:
File "C:\Python27\Lib\site-packages\bottle-0.10.9-py2.7.egg\bottle.py", line 1669, in __setitem__
def __setitem__(self, key, value): self.dict[_hkey(key)] = [str(value)]
请帮助。
Regard,
Omer。
Regard, Omer.
瓶正在尝试将HTTP响应上的 Content-Disposition
标头设置为附件; filename = ...
。这不适用于非ASCII字符,因为Bottle在内部使用 str
处理HTTP标头...但是即使没有,也没有跨浏览器-设置 Content-Disposition
和非ASCII 文件名
的兼容方法。 (背景。)
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.)
您可以将 download ='...'
设置为仅ASCII的安全字符串,以覆盖Bottle的默认猜测(使用包含Unicode的本地文件名。)
You could set download='...'
to a safe ASCII-only string to override Bottle's default guess (which is using the local filename, containing Unicode).
或者,省略 download
参数,并依靠浏览器的猜测URL末尾的文件名。 (这是获取Unicode下载文件名的唯一广泛兼容的方法。)不幸的是,然后Bottle将完全省略 Content-Disposition
,因此请考虑将返回的响应的标头更改为include普通 Content-Disposition:附件
,不带文件名。或者,也许您不在乎,如果 Content-Type
是始终可以下载的内容。
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.