UnicodeEncodeError: 'ascii'编解码器无法编码字符u'\xe9'

3

我正在Django 1.5的views.py中处理ajax脚本。在构建我的json文件后,我必须将用户名放入cookie中。该名称带有法语口音,例如'hervé'。以下是我的部分代码:

if user.is_active:
            login(request, user)
            name = 'Hervé'
            jsondict['success'] = True
            jsondict['text']['welcome'] = 'Bienvenue, %s!' % name

            if name:
                fn = name
    response = HttpResponse(json.dumps(jsondict, cls=DjangoJSONEncoder, ensure_ascii=False),mimetype='application/json')
    if fn:
        set_cookie(response,"full_name",fn)

出现的错误是:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 4: ordinal not in range(128)

为解决这个问题,我使用了unicode()和decode()等方法,但是并没有改变任何东西。这个错误来自set_cookie()函数还是json文件呢?我应该怎么做才能解决它呢?
这是set_cookies函数:
def set_cookie(response, key, value, days_expire = 7):
import datetime
from django.conf import settings
if days_expire is None:
    max_age = 365 * 24 * 60 * 60  #one year
else:
    max_age = days_expire * 24 * 60 * 60 
expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None)

jsondict['text']['welcome'] = u'欢迎,%s!' % (user.get_full_name(),) - Joran Beasley
如何使用常量?像这样吗? cnst = u'Bienvenue, %s!' % (user.get_full_name(),) jsondict['text']['welcome'] = cnst - Hervé
blah = '一些包含Unicode的文本!' 这样的例子,基本上可以让我们运行。 - Joran Beasley
我认为如果你能包含完整的堆栈跟踪而不仅仅是错误消息,那将非常有用。 - jogojapan
@jogojapan 我更新了跟踪 http://pastebin.com/hNAjh7jd - Hervé
1个回答

1

好的,现在我已经修复了。在您的views.py文件头部,添加这个解释器。

# -*- coding: latin-1 -*-

在你的函数中,
name = 'Hervé'
name.decode('latin-1').encode('ascii','xmlcharrefreplace') //add this line
jsondict['success'] = True
jsondict['text']['welcome'] = 'Bienvenue, %s!' % name

好的,我会尝试找到解决方案。 - catherine
它不起作用。我认为错误不在JSON文件中,而是在set_cookies函数中。或者我错了? - Hervé
当我测试你的原始代码时,我遇到了相同的错误。所以我使用解释器来解释ASCII码。也许你应该更多地搜索相关信息。那些代码在我的电脑上可以运行。 - catherine
你是对的,你的代码可以工作,但我认为它不能在我的电脑上运行的原因是名字“hervé”来自数据库,而Python编码为u'hervé' (u'herv\xe9')。 - Hervé
不,不是这样的。我认为它会起作用,换个思路想一想。我不能给你一个固定的解决方案,因为我不了解你的项目。 - catherine
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接