在Python中使用protobuf2.6.1 string format utf-8 and unicode error
版本信息:
protobuf: v2.6.1
python: 2.7
关于在Python中使用protobuf时 string格式字段的编码问题
在python中编码格式多采用utf-8格式。而protobuf
官网中这样说到:

如果不做处理,在message 中定义了一个string类型的字段后,出现错误如下:
ERROR: ValueError: '\xe5\x94\x90\xe6\x9e\x9c' has type bytes, but isn't in 7-bit ASCII encoding. Non-ASCII strings must be converted to unicode objects before being added.
解决办法有两种。如下:
1) 一劳永逸的方法-修改源码
a. 文件../google/protobuf/internal/decoder.py
def StringDecoder(field_number, is_repeated, is_packed, key, new_default):
"""Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint
local_unicode = unicode def _ConvertToUnicode(byte_str):
try:
#return local_unicode(byte_str, 'utf-8') # 注释掉 不转码
return byte_str
except UnicodeDecodeError, e:
# add more information to the error message and re-raise it.
e.reason = '%s in field: %s' % (e, key.full_name)
raise
b. 文件../google/protobuf/internal/type_checkers.py
class UnicodeValueChecker(object): """Checker used for string fields. Always returns a unicode value, even if the input is of type str.
""" def CheckValue(self, proposed_value):
if not isinstance(proposed_value, (bytes, unicode)):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), (bytes, unicode)))
raise TypeError(message) # If the value is of type 'bytes' make sure that it is in 7-bit ASCII
# encoding.
# if isinstance(proposed_value, bytes):
# try:
# proposed_value = proposed_value.decode('ascii')
# except UnicodeDecodeError:
# raise ValueError('%.1024r has type bytes, but isn\'t in 7-bit ASCII '
# 'encoding. Non-ASCII strings must be converted to '
# 'unicode objects before being added.' %
# (proposed_value))
return proposed_value
2) 很烦的方法-手动转码
在message中赋值时 都带上 decode("utf-8")
在Python中使用protobuf2.6.1 string format utf-8 and unicode error的更多相关文章
- python中date、datetime、string的相互转换
		
import datetime import time string转datetime str = '2012-11-19' date_time = datetime.datetime.strptim ...
 - python中dict对象和字符串string对象互相转换
		
使用json包 import json dict1 = {"A":"a","B":"b"} # 转换为字符串 json. ...
 - python中string的操作函数
		
在python有各种各样的string操作函数.在历史上string类在python中经历了一段轮回的历史.在最开始的时候,python有一个专门的string的module,要使用string的方法 ...
 - Python中print用法里面% ,"%s 和 % d" 代表的意思
		
Python 编程 里面% . "%s 和 % d" 代表的意思 %s,表示格化式一个对象为字符 %d,整数 "Hello, %s"%"zhang3& ...
 - Lua中string.format占位符的使用
		
虽然lua中字符串拼接"string.format"相对于".."消耗较大,但有时为了代码的可读性,项目中还是经常用到"string.format&q ...
 - C# string.Format谨慎使用
		
string.Format string.Format在处理文本的时候很有用处,但是在使用占位符的时候一定要注意内容中的特殊字符{}. 示例 string.Format("你好{0},这是{ ...
 - python中string.casefold和string.lower区别
		
string.casefold和string.lower 区别 python 3.3 引入了string.casefold 方法,其效果和 string.lower 非常类似,都可以把字符串变成小写, ...
 - 牛人总结python中string模块各属性以及函数的用法,果断转了,好东西
		
http://blog.chinaunix.net/uid-25992400-id-3283846.html http://blog.csdn.net/xiaoxiaoniaoer1/article/ ...
 - java和python中的string和int数据类型的转换
		
未经允许,禁止转载!!! 在平时写代码的时候经常会用到string和int数据类型的转换 由于java和python在string和int数据类型转换的时候是不一样的 下面总结了java和python ...
 
随机推荐
- [BZOJ2870]最长道路tree:点分治
			
算法一:点分治+线段树 分析 说是线段树,但是其实要写树状数组卡常. 代码 #include <bits/stdc++.h> #define rin(i,a,b) for(register ...
 - easyui 功能列传递一行数据
			
DeleteRow(' + JSON.stringify(row).replace(/"/g, '"') + ',0,' + Pindex + ',' + index + ')
 - Jmeter -- 上下文关联(JSON提取器)
			
目标: 将请求A响应数据的部分内容提取出来,保存成变量供后续请求使用(用在返回格式为json的HTTP请求中) 步骤: 1. 添加JSON Extractor后置处理器 add --> post ...
 - intellij idea中去除@Autowired注入对象的红色波浪线提示
			
idea中通过@Autowired注入的对象一直有下划线提示. 解决:改变@Autowired的检查级别即可. 快捷键:Ctrl+Alt+s,进入idea设置界面,输入inspections检索
 - HDU 2243  ( Trie图  矩阵构造幂和 )
			
题意 : 长度不超过L,只由小写字母组成的,至少包含一个词根的单词,一共可能有多少个呢?这里就不考虑单词是否有实际意义. 比如一共有2个词根 aa 和 ab ,则可能存在104个长度不超过3的单词, ...
 - layer系列之table导出+打印功能总结
			
1.关于layui导出方式,直接使用layui(版本2.4.5及以上)自带的导出方法即可: layui官网地址:https://www.layui.com/ 源码如下: <!DOCTYPE ht ...
 - tensorflow源码分析——CTC
			
CTC是2006年的论文Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurren ...
 - 【ASK】设置网卡启动遇到的事!
			
上次动笔是16年的事情了,一晃3年过去了.算了,不感慨了.直奔主题吧. 1.今天朋友要把一批win10的机器设置成网卡启动. 2.网卡是intel集成的. 3.按照主板说明已经设置成功. 4.通过wi ...
 - vim字体设置
			
经过多方试验,在win下设置vim的大小终于成功了,备份如下, 现在把gvim7.1更改字体的方法记录如下,一段时间后,可能会失效,对他人造成困扰吧?!^_^ 在_vimrc中写:set guif ...
 - ping: sendto: No route to host
			
root@tuhooo:/home/ # ping www.baidu.comPING www.a.shifen.com (61.135.169.125): 56 data bytesping: se ...