首页 > 编程语言 >python2 http响应中文显示unicode \uXXX的问题

python2 http响应中文显示unicode \uXXX的问题

时间:2024-04-26 10:45:47浏览次数:18  
标签:http chunk write json ensure unicode uXXX ascii

python2编码解码会以unicode作为中间码,要用decode和encode解码后再编码
其中decode解码,是把bytes以给定的编码格式解码成unicode
encode是以给定的编码格式将unicode编码为bytes
数据是以bytes形式传递和存储的,程序需要用正确的编码来将bytes解码显示
decode: From bytes To Unicode
encode: From Unicode To bytes

在python2中试了多种编解码组合,都无法解决中文显示为unicode形式的问题
最终发现是http框架对json数据做序列化的时候出的问题

python-json 相关代码注释如下

def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
        allow_nan=True, cls=None, indent=None, separators=None,
        encoding='utf-8', default=None, sort_keys=False, **kw):
    """Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
    ``.write()``-supporting file-like object).

    If ``skipkeys`` is true then ``dict`` keys that are not basic types
    (``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
    will be skipped instead of raising a ``TypeError``.

    If ``ensure_ascii`` is true (the default), all non-ASCII characters in the
    output are escaped with ``\uXXXX`` sequences, and the result is a ``str``
    instance consisting of ASCII characters only.  If ``ensure_ascii`` is
    false, some chunks written to ``fp`` may be ``unicode`` instances.
    This usually happens because the input contains unicode strings or the
    ``encoding`` parameter is used. Unless ``fp.write()`` explicitly
    understands ``unicode`` (as in ``codecs.getwriter``) this is likely to
    cause an error.

其中有关于 ensure_ascii 参数的说明
大意就是,如果ensure_ascii为true,任何非ascii字符都会被转义成\uXXXX的形式
再看tornado中write方法的代码, write方法对dict类型数据统一用escape.json_encode序列化为json
两个方法代码如下

    def write(self, chunk):
        if self._finished:
            raise RuntimeError("Cannot write() after finish()")
        if not isinstance(chunk, (bytes, unicode_type, dict)):
            message = "write() only accepts bytes, unicode, and dict objects"
            if isinstance(chunk, list):
                message += ". Lists not accepted for security reasons; see http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler.write"
            raise TypeError(message)
        if isinstance(chunk, dict):
            chunk = escape.json_encode(chunk)
            self.set_header("Content-Type", "application/json; charset=UTF-8")
        chunk = utf8(chunk)
        self._write_buffer.append(chunk)
    ===================================================
    def json_encode(value):
        return json.dumps(value).replace("</", "<\\/")

可以看到json_encode中 json dumps方法并没有给定ensure_ascii的值,所以ensure_ascii就是默认值True,也就是,被序列化的数据中的字符串所有非ascii的字符都会转义为unicode形式。

解决办法,就是手动处理json数据,将ensure_ascii设定为False。

json.dumps(value, ensure_ascii=False)

老项目没办法,新项目必定是python3了。


https://www.cnblogs.com/haiton/p/18159481
转载须注明出处!!!!

标签:http,chunk,write,json,ensure,unicode,uXXX,ascii
From: https://www.cnblogs.com/haiton/p/18159481

相关文章

  • 记录一个HttpClient超时连接配置不生效的问题排查过程
    现象首先有一个被服务由于内存有限,导致巨卡。导致调用他的服务出现线程阻塞。jstack打印线程池如下所示:开始排查解决问题第一步:检查代码看是否超时设置是否正确,因为感觉超时设置正确不可能阻塞。找到注入client的位置:发现配置没有任何问题,此时感到了一点点慌张。(内心OS:......
  • SQL SERVER中的字符类型使用Unicode
    字符编码和排序规则下面的讨论用到W、王和......
  • gRPC和HTTP的对比
    概述gRPC和HTTP是两种常见的网络通信协议,用于在客户端和服务器之间进行通信。它们具有不同的特点和适用场景,下面进行详细比较。HTTP(HypertextTransferProtocol)特点简单易用:HTTP使用简单的请求方法和状态码来进行通信,如GET、POST、200OK、404NotFound等。它易于理......
  • javascript高级编程系列 - 使用XMLHttpRequest发送请求
    XMLHttpRequest通过XMLHttpRequest发送get请求//创建XMLHttpRequest实例对象constxhr=newXMLHttpRequest();//监听通信状态xhr.onreadystatechange=function(){//请求结束,处理服务器返回的数据if(xhr.readyState===4){//http状态码为200表示成功......
  • 碎片和水位线回收的验证过程 转发 https://www.modb.pro/db/1780420808865845248
    1、数据库基础内容表空间-数据文件-段-区-块一个表空间由一个或者多个数据文件组成高水位线和表碎片的示意图其中被划掉的字代表delete删除,其中耶就是后续的insert,只会在末尾增加,而不是填充被删除的字段,这样就会导致数据库在搜寻数据时会浪费很多资源。整理碎片后大概是这......
  • HttpClient 爬去网络数据
    创建HttpHelper类publicclassHttpHelper{publicstaticHttpClientClient{get;}=newHttpClient();///get请求url请求地址publicstaticasyncTask<string>GetHTMLByURLAsync(stringurl,stringname=""){using(HttpClientclient=......
  • 使用Spring HttpExchange替代FeignClient进行http远程服务调用
    背景springboot3.0使用的springframework6.0里有一个全新的http服务调用注解@HttpExchange,该注解的用途是可以进行申明式http远程服务调用。与Feign作用相同,在springboot3.x里,由于本身spring内置,相比Feign可以大幅减少第三方包依赖,且比Feign进轻巧。依赖:@HttpExchange位......
  • https://github.com/meta-llama/llama3 文生图
    https://github.com/meta-llama/llama3 Skiptocontent NavigationMenu Product Solutions OpenSource Pricing Searchorjumpto...  SigninSignup  meta-llama/llama3PublicNotificationsFork 1.4k Star ......
  • 【Maven】解决 Since Maven 3.8.1 http repositories are blocked.问题
    【Maven】解决SinceMaven3.8.1httprepositoriesareblocked.问题在你本地setting.xml文件中 附上这段,然后mvnclean后,重新Reimport就可以了  <!--解决SinceMaven3.8.1httprepositoriesareblocked.问题--><mirrors><mirro......
  • Mysql:canal-deployer:如何阻断canal-client对deployer上的filter过滤条件订阅修改:https
     也算是安全管理上的一个控制点:本来,允许客户端去根据自己的实际需求去服务端订阅自己关心的数据流,是很好的。but,但是,服务端的黑白名单过滤,尤其是白名单的filter条件会被客户端的最新订阅的过滤条件给覆盖!!!这算是bug吗?上游服务端怎么显得那么没地位呢!!!??? #===================......