python - Redisco ListField unicode 保存错误但验证为真

标签 python unicode character-encoding redis redis-py

class Article(models.Model):
       title = models.Attribute()
       tags = models.ListField(unicode)

 new = Article(title='what ever')
 new.tags = [ u'Niña', u'Niñb' ]

 new.is_validate()
 >>> True

 new.save()

加载时:

Article.objects.all()

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)

在 redis-cli 中:

redis 127.0.0.1:6379> GET "Article:tags:5omv5reh"
(error) ERR Operation against a key holding the wrong kind of value

那么是什么原因造成的呢?

最佳答案

所以经过尝试,unicode字符串应该总是被编码并保存为字符串。 get时总是decode。代码来了:

class Article(models.Model):
       title = models.Attribute()
       tags = models.ListField(str)

 new = Article(title='what ever')
 new.tags = [ u'Niña'.encode('utf-8'), u'Niñb'.encode('utf-8') ]

 new.is_validate()
 >>> True

 new.save()

打印时:

 articles = Article.objects.all()
 for i in articles:
     print i.decode('utf-8')

关于python - Redisco ListField unicode 保存错误但验证为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20413315/

相关文章:

python - 无法在Python中的中文字符串中逐字符打印

java - 如何替换 url 中的 unicode 字符串以获得 json 响应?

java - 如何将整数转换为 base64 (0-9A-Za-z)

python - 使用 Python 脚本在 Ubuntu 终端中显示 UTF 8 字符串

ruby-on-rails-3 - ruby on Rails Actionmailer接收字符编码问题

python - 使用列表与由函数创建的列表

python - 使用 Anaconda/Miniconda Python 设置 Atom 包(即 Autocomplete-Python)中的 Python 可执行路径

python - Insert 语句不适用于数据类型不匹配的情况

python - 如何在 PyTorch 中修剪小于阈值的权重?

unicode - 有没有办法确定 Unicode 字符浏览器兼容性?