Python3处理grpc接口返回包含中文编码的protobuf数据时的显示问题

[本文出自天外归云的博客园]

当你用python调用grpc接口的时候,返回的protobuf数据中如果含有中文,会显示成编码模式,类似“\345\214\227\344\272\254”,如何显示成中文呢?这里有两种办法:

# 方法一:对 grpc 接口返回的包含中文编码的整体内容进行处理
def first_method(self, req):
    response = self.client.DoSomeRPCRequest(req)
    from google.protobuf.json_format import MessageToJson

    j = MessageToJson(response)
    a = json.loads(j)
    print(a)

def convert_string_to_bytes(string):
    import struct

    bytes = b""
    for i in string:
        bytes += struct.pack("B", ord(i))
    return bytes

# 方法二:对某个包含中文编码的字符串进行处理
def sec_method():
    a = "\345\214\227\344\272\254"
    b = convert_string_to_bytes(a)
    print(b.decode())

你学会了吗?

posted @ 2022-08-29 21:56  天外归云  阅读(474)  评论(0编辑  收藏  举报