google protocol buffer在python中使用utf-8的问题

google protocol buffer好用,但是在python中会有一些小问题。比如不支持utf-8只支持unicode的字符串。在我们的系统中,存储的和传输的都是utf-8,因此在代码中(c++,java,python)都统一使用utf-8格式。所以就带来不方便,比如c++中需要从utf-8转为unicode,python中再解析出来。实际上,可以让google protocol buffer for python不进行转码。

我遇到的问题是:c++读取文件(文件时utf-8的),然后python接受,c++发送的是utf-8的,但是python却要求unicode的,巨郁闷。

对于string类型的描述如下,说utf-8和ascii都支持,实际上python版本的却要求unicode,实在是可笑,由此可见,实际上试一下比说啥都强。

stringA string must always contain UTF-8 encoded or 7-bit ASCII text.stringString


下载google protocol buffer的源码,如 http://code.google.com/p/protobuf/downloads/list,下载2.0.3版本。
进入/protobuf-2.0.3/python/google/protobuf/internal目录下
encode.py
  1.   def AppendString(self, field_number, value):
  2.     """Appends a length-prefixed unicode string, encoded as UTF-8 to our buffer,
  3.     with the length varint-encoded.
  4.     """
  5. #  self.AppendBytes(field_number, value.encode('utf-8'))
  6. #  将value.encode去掉,我本来就是utf-8,干吗还编码呢
  7.     self.AppendBytes(field_number, value)

decode.py
  1.   def ReadString(self):
  2.     """Reads and returns a length-delimited string."""
  3.     bytes = self.ReadBytes()
  4. #    return unicode(bytes, 'utf-8')
  5. #    改为下面这句,啥也不干,是什么编码就返回什么编码
  6.     return bytes
type_check.py
  1. class UnicodeValueChecker(object):
  2.   """Checker used for string fields."""
  3.   def CheckValue(self, proposed_value):
  4.     if not isinstance(proposed_value, (str, unicode)):
  5.       message = ('%.1024r has type %s, but expected one of: %s' %
  6.                  (proposed_value, type(proposed_value), (str, unicode)))
  7.       raise TypeError(message)
  8.     # If the value is of type 'str' make sure that it is in 7-bit ASCII
  9.     # encoding.
  10.     # 莫名其妙,为何要try convert to unicode,而且是从ascii转,注释掉
  11. #    if isinstance(proposed_value, str):
  12. #      try:
  13. #        unicode(proposed_value, 'ascii')
  14. #      except UnicodeDecodeError:
  15. #        raise ValueError('%.1024r isn/'t in 7-bit ASCII encoding.'
  16. #                         % (proposed_value))

改了之后,重新安装一下,它就不会给你转编码了,你想传什么编码就什么编码。我用过c++版本的,好像不会处理编码问题。不过好像proto的数据类型中bytes也能满足要求,bytes它是不做任何处理的。




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值