gpt4 book ai didi

python - 奇怪的 `UnicodeEncodeError` 使用 `os.path.exists`

转载 作者:太空狗 更新时间:2023-10-29 17:28:55 25 4
gpt4 key购买 nike

在网络应用程序(使用 Flask)中,出现以下错误:

Unable to retrieve the thumbnail for u'/var/data/uploads/2012/03/22/12 Gerd\xb4s Banjo Trio 1024.jpg'
Traceback (most recent call last):
File "/var/www/beta/env/lib/python2.7/site-packages/dblib-1.0dev3-py2.7.egg/dblib/orm/file.py", line 169, in get_thumbnail
if not exists(filename):
File "/usr/lib/python2.7/genericpath.py", line 18, in exists
os.stat(path)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb4' in position 52: ordinal not in range(128)

请注意,我在记录的错误中包含了文件名的 repr()。这表明文件名作为 Unicode 实例传递。这么多是正确的...

如果我使用 python 解释器运行罪魁祸首,它会按预期工作:

>>> from os.path import exists
>>> exists(u'/var/data/uploads/2012/03/22/12 Gerd\xb4s Banjo Trio 1024.jpg')
True

很明显,在 Flask 环境中运行时,Python 认为它应该使用 ASCII 编解码器而不是 UTF-8 对文件名进行编码。我在 Apache httpd 后面使用 mod_wsgi 部署了应用程序。

我假设我必须告诉他们中的任何一个在某处使用 UTF-8?但是在哪里呢?

最佳答案

有关相同问题,请参阅 Django 文档。当使用 mod_wsgi 时,应该是相同的解决方案:

https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi/#if-you-get-a-unicodeencodeerror

上述链接文档的摘录:

[...] you must ensure that the environment used to start Apache is configured to accept non-ASCII file names. If your environment is not correctly configured, you will trigger UnicodeEncodeError exceptions when calling functions like the ones in os.path on filenames that contain non-ASCII characters.

To avoid these problems, the environment used to start Apache should contain settings analogous to the following:

export LANG='en_US.UTF-8'
export LC_ALL='en_US.UTF-8'

Consult the documentation for your operating system for the appropriate syntax and location to put these configuration items; /etc/apache2/envvars is a common location on Unix platforms. Once you have added these statements to your environment, restart Apache.

关于python - 奇怪的 `UnicodeEncodeError` 使用 `os.path.exists`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10396141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com