zoukankan      html  css  js  c++  java
  • python---补充django中文报错(2),Django3.5出错

    今天是要Django3.5设置项目,结果出现中文报错,虽然之前分析过py2.7的报错原因,但是在py3之后reload不在使用,需要引入:

    from importlib import  reload

    但是这个并没有任何用,因为在py3之后默认编码不再是字节码,而是utf-8,可以使用代码查看

    sys.getdefaultencoding()

    这时候就出现了新的错误,出错地点

    data = data.encode() AttributeError: 'bytes' object has no attribute 'encode

    原本抱着不去修改源码的态度,找找其他解决办法,但是找了半天,结果没找到.....。而且这也不是因为中文问题了,这尼玛刚刚说了,已默认utf-8编码了,

    所以算了,直接修改源码看看如何

        def finish_response(self):
            """Send any iterable data, then close self and the iterable
    
            Subclasses intended for use in asynchronous servers will
            want to redefine this method, such that it sets up callbacks
            in the event loop to iterate over the data, and to call
            'self.close()' once the response is finished.
            """
            try:
                if not self.result_is_file() or not self.sendfile():
                    for data in self.result:
                        # data = data.encode()
                        self.write(data)
                    self.finish_content()
            finally:
                self.close()

    结果居然成功了。

    再调试一下,看看原因

                    for data in self.result:
                        print(data,type(data))  #发现这个数据原本类型就是字节型,不需要我们再次进行编码。而且字节型也没有这个属性,这就是报错的原因
                        # data = data.encode()
                        self.write(data)
                    self.finish_content()        
  • 相关阅读:
    HTML5
    HTML5
    HTML5
    HTML5
    HTML5
    HTML5
    HTML5
    HTML5
    HTML5
    53.Maximum Subarray
  • 原文地址:https://www.cnblogs.com/ssyfj/p/8732665.html
Copyright © 2011-2022 走看看