UnicodeEncodeError:'latin-1'编解码器无法编码位置56-58中的字符:序数不在范围内(256)

时间:2018-03-29 09:48:51

标签: python django utf-8

当我请求中文字符名称图像时,我收到了以下错误:

line 507, in handle_one_response
    result = self.application(self.environ, start_response)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/engineio/middleware.py", line 49, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 156, in __call__
    request = self.request_class(environ)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 80, in __init__
    path_info = get_path_info(environ)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 175, in get_path_info
    path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/')
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 224, in get_bytes_from_wsgi
    return value.encode(ISO_8859_1) if six.PY3 else value
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 56-58: ordinal not in range(256)

图片网址为:

http://localhost:8000/images/qiyun_admin_websitemanage/bannerreconmend/服务器.png

(并且url存在于我的数据库中,带有中文字符)

我搜索了SO,找到this post

它说

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

在我的Django项目中,我找不到添加这些代码的地方。

仅我settings.py中的配置代码:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_mine',
        'USER':'root',
        'PASSWORD':'root',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    }
}

那么,如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

this answer所述,网址中的有效字符集为

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=。“

应引用其他字符以确保它们将被正确处理。您可以使用urllib.parse.quote函数引用它们。

>>> filename = '服务器.png'
>>> quoted_filename = urllib.parse.quote(filename)
>>> print(quoted_filename)
%E6%9C%8D%E5%8A%A1%E5%99%A8.png

并在构建网址时使用引用的版本。