Python Django开发 异常及解决办法(三)

1.Django2.2报错’gbk’ codec can’t decode byte 0xa6 in position 9737

在使用Django时,可能会报错如下:

File "C:\Users\LENOVO\.virtualenvs\Django_Framework-wC9HNSeq\lib\site-packages\django\views\debug.py", line 94, in technical_500_response
    html = reporter.get_traceback_html()
  File "C:\Users\LENOVO\.virtualenvs\Django_Framework-wC9HNSeq\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html
    t = DEBUG_ENGINE.from_string(fh.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence
[24/Aug/2020 20:03:51] "GET / HTTP/1.1" 500 59
C:\Users\LENOVO\.virtualenvs\Django_Framework-wC9HNSeq\Lib\site-packages\django\views\debug.py changed, reloading.
Watching for file changes with StatReloader

提示django\views\debug.py332行GBK解码错误,即源码出错,此时只需要修改源码即可。
在PyCharm中按住Ctrl键鼠标移到File "C:\Users\LENOVO\.virtualenvs\Django_Framework-wC9HNSeq\lib\site-packages\django\views\debug.py", line 332, in get_traceback_html行(会有蓝色和下划线提示),即可打开源码,在331行和338行的open()方法中加入参数encoding="utf-8"即可,修改后如下:

    def get_traceback_html(self):
        """Return HTML version of debug 500 HTTP error page."""
        with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding="utf-8") as fh:
            t = DEBUG_ENGINE.from_string(fh.read())
        c = Context(self.get_traceback_data(), use_l10n=False)
        return t.render(c)

    def get_traceback_text(self):
        """Return plain text version of debug 500 HTTP error page."""
        with Path(CURRENT_DIR, 'templates', 'technical_500.txt').open(encoding="utf-8") as fh:
            t = DEBUG_ENGINE.from_string(fh.read())
        c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False)
        return t.render(c)

此时再运行就不会报错。

猜你喜欢

转载自blog.csdn.net/CUFEECR/article/details/108207448