版本信息:

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的更多相关文章

  1. python中date、datetime、string的相互转换

    import datetime import time string转datetime str = '2012-11-19' date_time = datetime.datetime.strptim ...

  2. python中dict对象和字符串string对象互相转换

    使用json包 import json dict1 = {"A":"a","B":"b"} # 转换为字符串 json. ...

  3. python中string的操作函数

    在python有各种各样的string操作函数.在历史上string类在python中经历了一段轮回的历史.在最开始的时候,python有一个专门的string的module,要使用string的方法 ...

  4. Python中print用法里面% ,"%s 和 % d" 代表的意思

    Python 编程 里面% . "%s 和 % d" 代表的意思 %s,表示格化式一个对象为字符 %d,整数 "Hello, %s"%"zhang3& ...

  5. Lua中string.format占位符的使用

    虽然lua中字符串拼接"string.format"相对于".."消耗较大,但有时为了代码的可读性,项目中还是经常用到"string.format&q ...

  6. C# string.Format谨慎使用

    string.Format string.Format在处理文本的时候很有用处,但是在使用占位符的时候一定要注意内容中的特殊字符{}. 示例 string.Format("你好{0},这是{ ...

  7. python中string.casefold和string.lower区别

    string.casefold和string.lower 区别 python 3.3 引入了string.casefold 方法,其效果和 string.lower 非常类似,都可以把字符串变成小写, ...

  8. 牛人总结python中string模块各属性以及函数的用法,果断转了,好东西

    http://blog.chinaunix.net/uid-25992400-id-3283846.html http://blog.csdn.net/xiaoxiaoniaoer1/article/ ...

  9. java和python中的string和int数据类型的转换

    未经允许,禁止转载!!! 在平时写代码的时候经常会用到string和int数据类型的转换 由于java和python在string和int数据类型转换的时候是不一样的 下面总结了java和python ...

随机推荐

  1. Zookeeper简介及安装(一)

    1 Zookeeper入门1.1 概述Zookeeper是一个开源的分布式的,为分布式应用提供协调服务的Apache项目. 1.2 特点 1.3 数据结构 1.4 应用场景提供的服务包括:统一命名服务 ...

  2. 如何将python源文件打包成exe文件

    PyInstaller是一个十分有用的第三方库,它能够在Windows.Linux.Mac OS X 等操作系统下将 Python 源文件打包,通过对源文件打包,Python 程序可以在没有安装 Py ...

  3. 【C++】关键字struct

    网址连接 https://www.cnblogs.com/zhengfa-af/p/8144786.html 主要内容: 1. C语言中,结构体的3中不同声明和定义方式: 2. struct在C和C+ ...

  4. mac 的 quickTime Player 设置播放速度

    按住 option 点击 下一个视频的图标每次调整幅度为0.1,大于 1.9 声音会消失. 按住 option+J 调慢播放速度 option+L 调快播放速度 每次调整幅度为0.1

  5. D. Restore Permutation

    D. Restore Permutation 就是给一个n个数的全排,然后bi记录比ai小且在排在ai前面的数的和,求ai 树状数组维护,二分 #include<bits/stdc++.h> ...

  6. C语言第四次实验报告

    第四次实验报告 一·实验项目名称: 多球反弹 二·实验项目功能描述: (1)实现多个小球 (2)实现多个小球碰壁会反弹 (3)实现小球之间碰撞反弹 三· 项目模块结构介绍 #define High 4 ...

  7. 编译rxtx

    https://blog.csdn.net/github_29989383/article/details/51886234 https://cloud.tencent.com/developer/a ...

  8. windows server 2008 r2 配置ftp (FileZilla Server )

    1.需要个ftp 2.在华为云内部,用IIS,配置后如果用主动模式,客户端需要配置后客户端需要做配置才能访问,去掉√,见下图. 3.华为云的教程,配被动需要把1024以上的端口都放开,不安全! 但客户 ...

  9. leetcode-mid-math-29. Divide Two Integers-NO

    mycode   91.28% class Solution(object): def divide(self, dividend, divisor): """ :typ ...

  10. 【flask_sqlalchemy】模糊查询

    flask_sqlalchemy的查询方法有filter()和filter_() 这2个方法的主要区别如下: 模块 语法 ><(大于和小于)查询 and_和or_查询 filter_by( ...